python - 如何使用 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)
解决方案
您可以通过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
推荐阅读
- python - Heroku ImportError:无法找到 zbar 共享库
- python - 创建类时,我得到 TypeError: missing 1 required position argument
- reactjs - 为什么我的 Firebase 会导致我超出最大调用堆栈大小
- typescript - 将装饰器添加到索引类型
- excel - excel按名称排序2列
- clickhouse - 使用 multiIf 修改字段
- swift - 带有标签图像和文本的 SwiftUI 菜单
- javascript - 在子组件中使用上下文 API 访问对象值
- php - Remove /?home/ from URL (Remove Controller Name from URL And Leave Only Method) | 代码点火器
- amazon-web-services - 描述成员 AWS 账户的 SCP 而不假设 AWS 管理账户