
파이썬으로 구글 이미지 크롤링을 해보았습니다.
"난 손이 빨라서 더 빨리 저장할 수 있는데?"라고 묻는 분이 계시다면,
1,000장이 되어도 동일한 속도로 저장할 수 있을지 되묻고 싶네요.
파이썬 초보자이지만, 구글링을 통해 부분부분 검색하여 코드를 완성하였습니다.
파이썬의 매력인 것 같습니다.
오늘도, 즐겁게 파이썬!
▼ 파이썬 코드 공개
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib.request
driver = webdriver.Chrome()
driver.get("https://www.google.co.kr/imghp?hl=ko&ogbl")
elem = driver.find_element_by_name("q")
elem.send_keys("박보검")
elem.send_keys(Keys.RETURN)
SCROLL_PAUSE_TIME = 1
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
try:
driver.find_element_by_css_selector(".mye4qd").click()
except:
break
last_height = new_height
images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
count = 1
for image in images:
try:
image.click()
time.sleep(2)
imgUrl = driver.find_element_by_xpath('/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div/div[2]/a/img').get_attribute("src")
urllib.request.urlretrieve(imgUrl, str(count) + ".jpg")
count = count + 1
except:
pass
driver.close()
|
cs |
(+ 추가)
유튜브에 댓글이 달렸었는데 18시간동안 확인을 안해서 그런지 작성자 분께서 삭제를 하셨다.

질문을 해결하기 위해서는 마지막 for 문 안에 if 문으로 갯수를 정하고 break 로 끝내면 된다.
count = count + 1 아랫줄에 다음 2줄을 넣으면 된다. 예를 들어서 10개를 수집하려면 10 + 1 개를 적으면 된다.
if count == 11:
break
(+ 추가) 유튜브에 질문 댓글이 달려 보완합니다.

'Python & SQL > Python Practice' 카테고리의 다른 글
| 기상청 공공데이터로 내 생일 기온 변화 그래프 그리기(feat. 주피터 노트북) (0) | 2021.03.31 |
|---|---|
| [문자열 웹 크롤링] 오늘의 띠별 운세 (0) | 2021.03.31 |
| 파이썬 자연 언어 처리(Natural Language Processing, NLP) 맛보기 (0) | 2021.03.29 |
| 파이썬 네이버 이미지 크롤링(Python Naver Image Crawling) (0) | 2021.03.24 |
| 파이썬 구구단 업그레이드 문제 ! (0) | 2021.03.23 |