유튜버 조코딩 님의 강의를 들으면 들을수록 너무 재미있다.
파이썬으로 네*버, 다*, 구* 등 실시간 검색순위 크롤링을 해보았다.
파이썬으로 크롤링하기!
클라우드형 구름IDE를 이용.
gmail과 연동되어 쉽게 가입가능.
왼쪽상단에 대시보드 -> 새 컨테이너 생성 -> 작성 후 컨테이너 실행 누르기
이름 : crawling (자신이 원하는 제목 작성)
지역 : 서울
공개범위 : public or private 원하는거 선택
스텍 : 파이썬
입장하면 crawling폴더에 index.py 파일에 코드작성
Beautiful soup 라이브러리 사용하기
구글에 beautiful soup 검색하면 위키백과에 예시코드 복사해서 붙여놓고 실행
from bs4 import BeautifulSoup
from urllib.request import urlopen
with urlopen('https://en.wikipedia.org/wiki/Main_Page') as response:
soup = BeautifulSoup(response, 'html.parser')
for anchor in soup.find_all('a'):
print(anchor.get('href', '/'))
코드 설명 :
위에서 불러운 urlopen으로 링크를 response에 담음.
with~ as~ 구문을 이렇게 직관적으로 바꿔도 같다.
response = urlopen('https://en.wikipedia.org/wiki/Main_Page')
beautiful soup 함수 이용해서 response 넣고 html.parser이용해서 분석한 다음 변수 soup에 담아줌
for 문 이용하여 soup에서 모든 a tag 찾아서 변수 anchor 에 넣는다.
anchor 를 하나씩 가져와서 주소를 프린트.
오류남(원인 : 모듈 설치되지 않아서)
해결 : 모듈 설치 명령창에 pip install bs4
*터미널에 패키지(라이브러리) 설치
pip install 패키지명
*BeautifulSoup : 크롤링용 라이브러리
*Pandas : 데이터 분석용 라이브러리
크롤링 실행!
네*버는 실시간 검색순위 크롤링 서비스가 html 방식에서 최근 json방시으로 바뀌면서 다른 방법으로 가져올 수는 있으나 다*으로 대체했다.
다음에 들어가 f12를 눌러 실시간 순위의 코드를 보고 활용.
response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
for anchor in soup.select("a.link_favorsch"):
print(anchor)
잘 오긴 하였으나
정리를 해보자.
print(soup.get_text())
.get을 활용하여 text만 뽑아온다.
from bs4 import BeautifulSoup
from urllib.request import urlopen
response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
for anchor in soup.select("a.link_favorsch"):
print(anchor.get_text())
+순위 넣기
i = 1
f = open("새파일.txt", 'w')
for anchor in soup.select("a.link_favorsch"):
print(str(i) + "위 : " + anchor.get_text())
i += 1
++텍스트 파일로 만들기
구글링 하니 '점프 투 파이썬'에 예제코드가 있었다:)
# writedata.py
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
오호~
from bs4 import BeautifulSoup
from urllib.request import urlopen
response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
i = 1
f = open("새파일.txt", 'w')
for anchor in soup.select("a.link_favorsch"):
data = str(i) + "위: " + anchor.get_text() + "\n"
i += 1
f.write(data)
f.close()
구글 이미지 크롤링
라이브러리 사용하여 사진 한번에 크롤링
python google image search and download 구글링 go go!
저기 눌러서 복사!
여기서 예제코드도 복사해 온다.
from google_images_download import google_images_download #importing the library
response = google_images_download.googleimagesdownload() #class instantiation
arguments = {"keywords":"Polar bears,baloons,Beaches","limit":20,"print_urls":True} #creating list of arguments
paths = response.download(arguments) #passing the arguments to the function
print(paths) #printing absolute paths of the downloaded images
복붙해주면 다운로드 된다.
google.py 새파일 생성.
예제코드 복붙!
라이브러리도 설치되었으니 바로 실행.
크롤링 재미있다 :)
'IT > Python' 카테고리의 다른 글
[python기초]로또 번호 생성하기 (0) | 2020.11.08 |
---|