我想使用selenium向下滚动网页。找到此:How can I scroll a web page using selenium webdriver in python?
获取此代码,如下所示:
SCROLL_PAUSE_TIME = 0.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);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# 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
它很好用。但是由于上面的代码,我在我的主代码中发现了一些问题。我想解析twitter。若twitter帐号很长,那个么在网页的html代码中会有一些twitter。不是这个帐户的所有twitter
示例:我向下滚动网页,网页的html代码中只包含对我可见(我可以看到)的twits。由于这件事,我不能抓住所有的傻瓜。上面的代码可以快速滚动页面。如何降低滚动速度
我试图解决这个问题,并编写了愚蠢的代码:
last_height = driver.execute_script("return document.body.scrollHeight")
print(last_height)
# Scroll down to bottom
y = 600
finished = False
while True:
for timer in range(0, 100):
driver.execute_script("window.scrollTo(0, " + str(y) + ")")
y += 600
sleep(1)
new_height = driver.execute_script("return document.body.scrollHeight")
print(new_height, last_height)
if new_height == last_height: #on the first iteration new_height equals last_height
print('stop')
finished = True
break
last_height = new_height
if finished:
break
这个代码不起作用。在第一次迭代中,新的高度等于最后的高度,请帮助我。
如果您可以修复我的代码,请修复它。如果你能写出另一个优雅的解决方案,请写出来
UPD:
这个滚动必须是无限的。例如:我向下滚动facebook帐户,直到完全滚动为止。这就是为什么我有last_height和new_height变量。在我的代码中,当last_height等于new_height时,这意味着页面已滚动到末尾,我们可以停止滚动(我们可以退出)。但是我错过了一些东西。我的代码不起作用
我在Twitter机器人上工作过,当你向下滚动时,它会更新页面的HTML并删除上面的一些推文。我使用的算法是:
current_height = DriverWrapper.cd.execute_script("return document.body.scrollHeight")
new_height == current_height
结束,则从第2步开始重复李>相关问题 更多 >
编程相关推荐