首页 > 解决方案 > 如何使用 Selenium 存储有关滚动时动态添加的 div 的信息?

问题描述

我目前正在尝试从网站skiplagged.com抓取数据。我目前正在尝试抓取数据的网页有大量对我有益的信息。

例如,假设网页上有关于 100 个航班的信息。尽管定位了正确的元素来获取信息,但我只设法获取了与 10 个航班相关的信息。

后来我意识到随着我不断向下滚动网页,新的 div 正在添加。结果,我无法抓取网页的其余部分。

早期的尝试

我还访问了这个链接,试图在页面末尾最终抓取数据:如何在 Python 中使用 selenium 滚动到页面末尾?

然而,我的尝试只产生了失败。

链接到我试图从中抓取数据的网页

https://skiplagged.com/flights/YTO/DXB/2020-08-21

我的 Python 代码

infinite_list = driver.find_elements_by_xpath("//div[@class='infinite-trip-list']//div[@class='span1 trip-duration']")
for elem in infinite_list:
    print(elem.text)

标签: pythonseleniumselenium-webdriverweb-scraping

解决方案


您可以通过execute_script一些调整来使用它

time.sleep(3) #sleeping to let the page load
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #scrolling down to the end

您还可以无限滚动直到页面结束

last = driver.execute_script("return document.body.scrollHeight")
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(1) #let the page load
    new = driver.execute_script("return document.body.scrollHeight")
    if new == last: #if new height is equal to last height then we have reached the end of the page so end the while loop
        break
    last = new #changing last's value to new

推荐阅读