크롤링을 하는 방법은 여러가지가 있다. 쉬운 순서대로 나열해보자면 아래와 같다.(내 기준)
1. api 를 통해 가져오는 방법
2. bs4를 사용하여 가져오는 방법
3. selenium 을 사용해 가져오는 방법
무한 스크롤 사이트인 경우에는 bs4를 통해서 한번에 가져올 수가 없다.
따라서 selenium 을 통해 최하단 페이지까지 가서 페이지를 긁어오는 방법을 사용해야겠다고 생각했다.
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
url = "crawling_site_url"
driver = webdriver.Chrome('chromedriver_path')
driver.get(url)
elem = driver.find_element_by_tag_name("body")
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
scroll_down = 0
while scroll_down < 10:
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2)
scroll_down += 1
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
print("********" + lecture['category'] + ' / ' + lecture['subCategory'] + " break********")
break
last_height = new_height
elem = driver.find_element_by_tag_name("body")
을 통해 우선 내용 부분을 elem 에 담는다.last_height = driver.execute_script("return document.body.scrollHeight")
을 통해elem.send_keys(Keys.PAGE_DOWN)
page down 버튼을 누르게해서 계속해서 페이지 하단으로 내려가는 코드.new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
만약 이전의 높이와 같다면 결국 최하단이라고 판단.last_height = new_height
이전의 높이와 다르다면 last_height 에 new_height 값을 넣어줘서 갱신시켜준다.