-
웹 브라우저 페이지를 자동으로 스크롤 해보기 (with 파이썬)코딩 연습/코딩배우기 2021. 12. 28. 21:22반응형
파이썬으로 selenium과 chrome webdriver를 사용하여 긴 웹 브라우저의 페이지를 자동으로 스크롤되게 하는 기능을 설명한다. 특히, 네이버 블로그의 경우 마우스를 내리면 계속해서 페이지가 스크롤되는데, 이에 대해 스크래핑(크롤링)할 때 유용하게 사용할 수 있다.
웹 브라우저 페이지 자동 스크롤링
▷url을 입력 시 웹 페이지 스크롤하는 함수
import time import random from selenium import webdriver from selenium.webdriver.common.keys import Keys def webpage_scroll(url): options = webdriver.ChromeOptions() options.add_argument('--headless') # 실행 화면 안 보이게 처리 options.add_argument('--disable-gpu') # 브라우저의 화면 렌더링 사용 안함 # user-agent 지정은 headless 탐지하는 것을 막기 위함 options.add_argument('user-agent = Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62') options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome('./chrome_driver/chromedriver.exe', chrome_options=options) driver.implicitly_wait(3) driver.get(url) elm_body = driver.find_element_by_tag_name('body') prev_height = driver.execute_script('return document.body.scrollHeight') # 현재 화면(웹 페이지) 높이 리턴 ## window.scrollTo(0, y) : 화면(웹 페이지) 지정 위치(y)로 스크롤 ## window.scrollTo(0,document.body.scrollHeight) : 화면(웹 페이지) 가장 아래로 스크롤 scroll_cnt = 0 while True: scroll_down = 0 for i in range(1, 11): elm_body.send_keys(Keys.PAGE_DOWN) # body 요소에 대해 PgDn키를 누름 print(f'Scrolling... {i}') time.sleep(random.uniform(0.1, 0.5)) scroll_down = i curr_height = driver.execute_script('return document.body.scrollHeight') scroll_cnt += scroll_down print(f'scroll_cnt: {scroll_cnt}, current_height: {curr_height}') if curr_height == prev_height: print('\last_height: ' + str(prev_height) + '\n') break else: prev_height = curr_height if scroll_cnt >= 20: break driver.get_screenshot_as_file('webpage_screenshot.png') driver.quit() return scroll_cnt, curr_height url = 'https://search.naver.com/search.naver?query=케스코&nso=&where=blog&sm=tab_opt' result = webpage_scroll(url) print(f'스크롤 수 : {result[0]}, Webpage Height : {result[1]}')
[결과]
Scrolling... 1 Scrolling... 2 Scrolling... 3 Scrolling... 4 Scrolling... 5 Scrolling... 6 Scrolling... 7 Scrolling... 8 Scrolling... 9 Scrolling... 10 scroll_cnt: 10, current_height: 8078 Scrolling... 1 Scrolling... 2 Scrolling... 3 Scrolling... 4 Scrolling... 5 Scrolling... 6 Scrolling... 7 Scrolling... 8 Scrolling... 9 Scrolling... 10 scroll_cnt: 20, current_height: 11858
크롬 옵션 중 options.add_experimental_option('excludeSwitches', ['enable-logging']) 부분은 "크롬 웹드라이브 '시스템에 부착된 장치가 작동하지 않습니다.' 메시지" 페이지 참조
테스트 페이지(네이버 블로그) 스크롤을 중간에 중단시키기 위해 while 문 마지막에 if 문 있음. 이 부분을 없앨 경우 해당 블로그 페이지 하단까지 가게 됨
if scroll_cnt >= 20:
break반응형'코딩 연습 > 코딩배우기' 카테고리의 다른 글
단축 URL 스크래핑에 파이썬 비동기 처리 개념 적용해보기 (0) 2022.01.07 selenium으로 네이버 쿠키를 얻고 세션을 유지하는 방법 (2) 2022.01.03 블로그 글 내용 저장 중 이모지 '\U0001f970' 에러 발생 (파이썬) (0) 2021.12.26 파이썬 selenium 라이브러리 - find_elements_by_* commands are deprecated. (0) 2021.12.25 크롬 웹드라이버 '시스템에 부착된 장치가 작동하지 않습니다.' 메시지 (0) 2021.12.25