我正在尝试使用硒无限滚动 此网页https://gfycat.com/discover/trending-gifs
我尝试以下代码:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(options=options, executable_path=r"C:\chromedriver.exe")
driver.get(url)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
driver.quit()
但是没有向下滚动。
我也尝试过:
from selenium.webdriver.common.keys import Keys
for i in range(10):
driver.find_element_by_css_selector('html').send_keys(Keys.END)
但是也没有发生向下滚动。
答案 0 :(得分:0)
对于无限滚动网站,您可以在Selenium中使用这种编码方法,因为您可以看到我正在使用while
进行无限滚动,此外,您应该导入time
模块以免加载网站
def scroll(driver):
timeout = 5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# load the website
time.sleep(5)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")