硒execute_script()返回不正确的值

时间:2018-08-08 05:49:08

标签: python selenium youtube selenium-chromedriver

我在下面的浮动页面(如https://www.youtube.com/user/JFlaMusic/videos)上使用python硒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

1 个答案:

答案 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")