我在下面的浮动页面(如https://www.youtube.com/user/JFlaMusic/videos)上使用python硒chromedriver执行了代码。但是代码执行不正确。
我原本希望转到页面的末尾,但是last_height
和new_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
答案 0 :(得分:1)
与其使用看起来不太可靠的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")