gpt4 book ai didi

selenium - 使用 selenium Python 滚动到无限加载页面的末尾

转载 作者:行者123 更新时间:2023-12-02 02:40:52 27 4
gpt4 key购买 nike

我正在使用 Selenium 从 Twitter 上抓取关注者姓名,该页面是无限的,每当我向下滚动时,我都能看到新的关注者。我想以某种方式转到页面底部,以便可以抓取所有关注者。

while number != 5:
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
number = number + 1
time.sleep(5)

usernames = driver.find_elements_by_class_name(
"css-4rbku5.css-18t94o4.css-1dbjc4n.r-1loqt21.r-1wbh5a2.r-dnmrzs.r-1ny4l3l")
for username in usernames:
print(username.get_attribute("href"))

现在代码滚动了 5 次。我设置了一个静态值,但我不知道需要滚动多少次才能到达页面底部。

最佳答案

使用下面的代码进行无限加载。它会一直滚动,直到加载新元素,即页面大小发生变化。

# Get scroll height after first time page load
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page / use a better technique like `waitforpageload` etc., if possible
time.sleep(2)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height

关于selenium - 使用 selenium Python 滚动到无限加载页面的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63647849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com