为什么使用 python selenium 的 execute_script("return document.body.scrollHeight") 返回 0

김정석*_*김정석 3 python selenium

在此处输入图像描述。下面是我的python代码。 get()运作良好。而表演后execute_script("return document.body.scrollHeight"),又lastHeight回来了0。chromedriver 网页上的移动是没有的。然后newHeight也返回0。他们为什么回来0

def getVideoData(self):
     self.chromeBrowser.get(self.videoTab)
     lastHeight = self.chromeBrowser.execute_script("return document.body.scrollHeight")
     print(lastHeight)
     while True:
        self.chromeBrowser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        self.chromeBrowser.implicitly_wait(0.5)
        newHeight = self.chromeBrowser.execute_script("return document.body.scrollHeight")
        print(newHeight)
        if newHeight == lastHeight:
           break
        lastHeight = newHeight
Run Code Online (Sandbox Code Playgroud)

图像显示了 get() 的正确结果。要显示图像,请单击“在此处输入图像描述”

Swa*_*r C 16

我假设您正在尝试使用 selenium 滚动到页面末尾。在分析该问题时,我发现 JavaScript 存在一个错误,document.body.scrollHeight该错误在 YouTube.com 等具有浮动网络元素的页面上出现故障。请参阅错误详细信息。我已经试过了document.documentElement.scrollHeight,它看起来很适合这个页面。

>>> driver.execute_script("return document.documentElement.scrollHeight")
3120
Run Code Online (Sandbox Code Playgroud)

话虽如此,以下指令证明可以滚动到页面末尾。

>>> height = driver.execute_script("return document.documentElement.scrollHeight")
>>> driver.execute_script("window.scrollTo(0, " + str(height) + ");")
Run Code Online (Sandbox Code Playgroud)

使用脚本滚动到页面底部

如果您想删除Chrome is being controlled by automated software信息栏,请使用以下命令启动浏览器。

chrome_options = Options()
chrome_options.add_argument('disable_infobars')
driver = webdriver.Chrome(chrome_options=chrome_options)
Run Code Online (Sandbox Code Playgroud)