大家好,我正在尝试使用 selenium 和 scrapy 从 https://answers.yahoo.com/dir/index/discover?sid=396545663 中抓取一些信息
我尝试不同的方法,我使用 Selenium 并设置 PhantomJs 像驱动程序。 对于向下滚动页面,这是一个无限滚动页面,我使用以下指令:
elem.send_keys(Keys.PAGE_DOWN)
用于模拟按下 Page Down 按钮,而不是 JavaScript 函数:
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
因为这个“似乎”在页面中加载了更少的元素。
主要的问题是我如何知道我何时到达页面底部?是“无限滚动”页面,所以我不知道它何时结束,我需要向下滚动,但底部没有任何元素可供分析。
实际上我使用临时循环,但看起来很愚蠢。
谢谢
最佳答案
我实际上会寻找“正在加载...”指示器。 Wait for it在每次滚动时都可见,但如果您收到 TimeoutException
- 这次没有加载指示器,并且没有更多项目要加载。
示例实现:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
while True:
# do the scrolling
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[. = 'Loading...']")))
except TimeoutException:
break # not more posts were loaded - exit the loop
未经测试。
关于javascript - Python 中使用 Selenium 停止动态页面滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939469/