동일한 레이아웃과 디자인을 유지하면서 각각 다른 내용을 display하는 Web Page (https://www.packetlabs.net/posts/dynamic-pages)
여기서 충분한 정보를 영화 1000개라고 가정하였고(너무 많이 가져 올 시 Memory 이슈 발생), 따라서 1000개의 영화가 쌓일 때까지 계속 스크롤을 내려야 했다.
영화 1000개가 쌓일 때까지 최대한 빠르게 스크롤을 내릴 방법을 생각해야 했는데 한번 내린 후 적절한 time.sleep()을 주는 방법밖에 떠오르지 않아 다른 방법을 찾아 보았다.
첫 번째 방법은 내가 찾고 싶은 element의 개수를 정한 뒤 그 개수만큼 정보가 쌓일 때까지 계속 스크롤을 내리는 방법이다.
num_movies = 0
while num_movies < 1000:
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
num_movies = len(driver.find_elements_by_class_name("css-8y23cj"))
두 번째 방법은 Web Page의 height를 기반으로 한다.
현재 Page의 height를 저장하고, 스크롤을 내린 후 new_height > last_height
를 충족할 때까지 Explicit wait한다.
class infine_scroll(object):
def __init__(self, last):
self.last = last
def __call__(self, driver):
new = driver.execute_script('return document.body.scrollHeight')
if new > self.last:
return new
else:
return False
last_height = driver.execute_script('return document.body.scrollHeight')
flag=1
while flag==1:
driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')
try:
wait = WebDriverWait(driver, 10)
new_height = wait.until(infinite_scroll(last_height))
last_height = new_height
except:
print("End of page reached")
flag = 0
첫 번째 방법으로 진행 시 1000개의 영화를 가져오는 데에 약 13분이 걸렸지만
두 번째 방법을 이용하니 약 8분 30초만에 더 이상 정보가 update 되지 않을 때까지 스크롤을 내렸고 무려 4200개의 영화를 가져왔다.
(두 방법 모두 무선 LAN 환경에서 진행되었음)
while True:
try:
driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')
except:
break