데이터 꿈나무
[데이터 청년 캠퍼스] 구글 이미지 자동 스크롤 웹크롤링 with Python 본문
안녕하세요 여러분~! 저번 시간에는 네이버 자동 스크롤 이미지 크롤링을 했었는데요, 이번 포스팅은 구글 이미지 크롤링을 해볼까 합니다!! 네이버 자동 스크롤 이미지 크롤링이 궁금하신 분들은 아래 URL을 확인해주세요:)
네이버와 비슷한 코드일거라고 생각을 하실 수도 있는데 조금..아니 많이 달라요ㅎㅎ 비슷하면 더 좋은텐데 그쵸??
구글 이미지 크롤링도 자동 스크롤 설정을 해놓아서 코드가 돌아가면서 이미지가 자동으로 한 폴더에 저장이 될 거예요~! 아 그리고 이번에도 스타벅스 ICED음료 사진을 종류별로 크롤링 해볼거랍니다. 시작해볼까요?!
https://risingdata.tistory.com/9
[데이터 청년 캠퍼스] 네이버 자동 스크롤 이미지 크롤링 with 파이썬(Python)
안녕하세요~! 저번 방학 때 대외활동 '데이터 청년 캠퍼스'에서 팀원들과 프로젝트를 하면서 네이버 자동 스르롤 이미지 크롤링을 해봤었는데요, 그때 작성한 코드 공유해드리려고 해요~ 제가
risingdata.tistory.com
모듈 임포트
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import os, time, random
from bs4 import BeautifulSoup
import urllib.request
우선 필요한 모듈을 임포트 해줄게요~ 저희가 해볼 크롤링에서는 위와 같은 모듈들이 필요하답니다.
셀레니움으로 크롬 브라우저를 적용하는 옵션
def chromeWebdriver():
options = Options()
options.add_argument("lang=ko_KR") # 언어 설정
# options.add_argument("start-maximized") # 창 크기 최대로
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_experimental_option('detach', True) # 브라우저 안 닫히게
options.add_experimental_option('excludeSwitches', ['enable-logging']) # 시스템 장치 에러 숨기기
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'
options.add_argument(f'user-agent={user_agent}')
# options.add_argument('--headless') # 웹 브라우저를 시각적으로 띄우지 않는 headless chrome 옵션
driver = webdriver.Chrome(service=Service(executable_path=ChromeDriverManager().install()), options=options)
return driver
셀레니움으로 크롬 브라우저를 적용하는 옵션들에 대해서 코드를 작성해볼게요.
여기에서 쓰이는 모듈은 아래와 같습니다.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
어떤 모듈이 어디에 쓰이는지 궁금하신 분들은 참고해주세요!
options.add_argument() 를 해주어 언어 설정을 해주었습니다.
저장 위치 만들어주기
def collect_image(search_word, extract_img_count):
url = 'https://www.google.co.kr'
now = time.localtime()
today_time = f'{now.tm_year}{now.tm_mon}{now.tm_mday}_{now.tm_hour}{now.tm_min}'
print(today_time)
file_path = "C:/Python/instagram img crawling/img"
os.chdir(file_path)
os.makedirs(file_path + today_time + '_' + search_word)
os.chdir(file_path + today_time + '_' + search_word)
file_save_dir = file_path + today_time + '_' + search_word
print(file_save_dir)
driver = chromeWebdriver()
driver.get(url)
time.sleep(random.uniform(2, 3))
elem_q = driver.find_element(By.NAME, 'q')
elem_q.send_keys(search_word)
elem_q.submit()
driver.find_element(By.LINK_TEXT, '이미지').click() # 텍스트 메뉴 '이미지' 링크 클릭
# driver.find_element(By.XPATH, '//*[@id="hdtb-msb"]/div[1]/div/div[2]/a').click()
time.sleep(random.uniform(1, 2))
구글 홈페이지에 접근하여 시간을 걸어주고, 사진 파일을 저장할 위치를 정해주었습니다.
※ os.chdir : Directory의 위치를 바꿔줌
※ os.makedirs : Directory 생성(폴더 안에 폴더 생성 가능)
그 후, driver.find_element를 이용하여 텍스트 메뉴 '이미지' 링크를 클릭하도록 하였습니다.
페이지 스크롤 다운
# 페이지 스크롤 다운
def page_scrolling(drivers):
## scrolling ------------------------------
elem = driver.find_element(By.TAG_NAME, 'body')
page_height = driver.execute_script('return document.body.scrollHeight')
# print(page_height)
# more_view_cnt = 0
scroll_cnt = 1
more_view_scroll_cnt = -1 # '결과 더보기' 버튼 나올 때의 scroll_cnt (break 처리 위해 사용)
equal_cnt = 1
while True:
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(random.uniform(0.3, 0.5))
new_height = driver.execute_script('return document.body.scrollHeight')
if page_height != new_height:
page_height = new_height
equal_cnt = 1
print(f'scroll_cnt: {scroll_cnt}, new_height: {new_height}, equal_cnt: {equal_cnt}')
try:
scroll_cnt += 1
equal_cnt += 1
driver.find_element(By.XPATH, '//*[@id="islmp"]/div/div/div/div[1]/div[2]/div[2]/input').click() # 결과 더보기 버튼 처리
print('결과 더보기 버튼 클릭 처리')
more_view_scroll_cnt = scroll_cnt
more_view_cnt += 1
except:
if equal_cnt == 20: # scroll_cnt / more_view_scroll_cnt > 2.5:
break
continue
## End of scrolling ------------------------------
page_scrolling(driver)
file_no = 1
count = 1
img_src = []
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
# print(soup)
# imgs = driver.find_elements(By.TAG_NAME, 'img')
imgs = driver.find_elements(By.CSS_SELECTOR, '#islrg > div.islrc > div a.wXeWr.islib.nfEiy')
print(len(imgs))
for img in imgs:
img_src1 = img.click() # 이미지 클릭 시 display 되는 url을 찾기 위해 클릭함
try:
img_src2 = driver.find_element(By.CSS_SELECTOR, '#Sva75c > div > div > div.pxAole > div.tvh9oe.BIB1wf > c-wiz > div > div.OUZ5W > div.zjoqD > div.qdnLaf.isv-id > div > a')
except Exception:
continue
time.sleep(random.uniform(0.2, 0.5))
img_src3 = img_src2.find_element(By.TAG_NAME, 'img').get_attribute('src')
if img_src3[:4] != 'http':
continue
print(count, img_src3, '\n')
img_src.append(img_src3)
if count == extract_img_count + 10: # 이미지 에러 대비해서 입력 숫자보다 크게 잡음
break
count += 1
print(f'\n{"="*10} 추출한 전체 리스트 {"="*10}\n{img_src}\n\n{"="*10}총 {len(img_src)}개 추출함{"="*10}\n')
for i in range(len(img_src)):
extention = img_src[i].split('.')[-1]
ext = ''
if extention in ('jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF'):
ext = '.' + extention
else:
ext = '.jpg'
try:
urllib.request.urlretrieve(img_src[i], str(file_no).zfill(3) + ext)
print(img_src[i])
except Exception:
continue
print(f'{file_no}번째 이미지 저장-----')
file_no += 1
if file_no - 1 == extract_img_count:
break
driver.close()
if __name__ == '__main__':
collect_image('민트 초콜릿 칩 블렌디드', 200)
● 추출된 이미지 URL 리스트를 대상으로 urllib.request.urlretrieve() 를 활용하여 이미지를 저장합니다.
'Activity > 데이터 청년 캠퍼스' 카테고리의 다른 글
| [데이터 청년 캠퍼스] CNN의 ResNet50 모델로 스타벅스 음료 이미지 분류 모델 구현 with Python (0) | 2022.12.25 |
|---|---|
| [데이터 청년 캠퍼스] CNN을 이용한 모델링(VGG16 모델) / 스타벅스 이미지 분류 모델 (2) | 2022.12.24 |
| [데이터 청년 캠퍼스] 딥러닝 VGG16 모델 구현 이미지 전처리 with Python (0) | 2022.12.23 |
| [데이터 청년 캠퍼스] 네이버 자동 스크롤 이미지 크롤링 with 파이썬(Python) (2) | 2022.09.25 |
| [데이터 청년 캠퍼스] Python 스타벅스 메뉴 영양성분 크롤링 (2) | 2022.09.17 |