问题描述
使用Python和Selenium时,我在滚动到网页顶部时遇到问题.
I'm having issues with scrolling to the top of the web page when using Python and Selenium.
当页面由于某种原因加载时,您将被带到页面底部(这是固定的).但是,当我尝试滚动到顶部时,它不起作用.
When the page loads for some reason you are taken to the bottom of the page (this is due to be fixed). However, when I'm trying to scroll to the top it does not work.
我尝试了以下操作:
self.driver.execute_script("scroll(0, -250);")
还有
self.driver.execute_script("scroll(0, 0);")
我还尝试过定位该元素,然后滚动到该元素:
I have also tried locating the element then scrolling to it:
self.driver.execute_script("arguments[0].scrollIntoView()", element)
当向下滚动到元素时,上面的scrollIntoView()代码有效.但是,它无法向上滚动.
The above scrollIntoView() code works when scrolling down to the element. However, it does not work scrolling up.
我已经尝试过运行Chrome驱动程序和PhantomJs.
I have tried this running Chrome Driver and PhantomJs.
有什么建议吗?
推荐答案
您可以考虑先在HTML DOM
中找到该元素,然后将scroll
元素放入 Viewport
如下:
You can consider to locate the element in the HTML DOM
first, then we can scroll
the element into the Viewport
as follows:
element = driver.find_element_by_xpath("element_xpath")
self.driver.execute_script("return arguments[0].scrollIntoView(true);", element)
这篇关于使用Selenium滚动到Python页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!