gpt4 book ai didi

python - seleniumexecute_script() 返回错误值

转载 作者:行者123 更新时间:2023-12-01 09:09:56 25 4
gpt4 key购买 nike

我在 float 页面上执行了下面的代码,例如 https://www.youtube.com/user/JFlaMusic/videos使用 python selenium chromedriver。但代码执行不正确。我原本希望转到页面末尾,但是 last_heightnew_height 在条件循环中一开始是相同的。所以执行了break。为什么会出现这样的结果?

last_height = self.driver.execute_script("return document.documentElement.scrollHeight")
print(last_height)
while True:
self.driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
time.sleep(0.5)
new_height = self.driver.execute_script("return document.documentElement.scrollHeight")
print(new_height)
if new_height == last_height:
break
last_height = new_height

最佳答案

不要使用看起来相当不可靠的 time.sleep(0.5),而是尝试按如下方式实现 ExplicitWait 来等待页面滚动:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException

last_height = self.driver.execute_script("return document.documentElement.scrollHeight")
print(last_height)
while True:
self.driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
try:
wait(self.driver, 5).until(lambda driver: self.driver.execute_script("return document.documentElement.scrollHeight") > last_height)
except TimeoutException:
break
last_height = self.driver.execute_script("return document.documentElement.scrollHeight")

关于python - seleniumexecute_script() 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51739413/

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