问题描述
我需要能够向上滚动,然后向下滚动才能找到带有Selenium的元素.
我已经看到很多问题和答案,我发现的主要思想是 self.web_driver.execute_script("return arguments [0] .scrollIntoView(true);",element)
,这是我目前拥有的在我的代码中.但这还不够好,因为此代码仅向下滚动,因此如果该元素位于可滚动视图的上部,则无法找到该元素.
所以我需要一个脚本,该脚本首先向上滚动(向上翻页?),然后开始向下滚动.
我尝试过这样的事情
I need to be able to scroll up and after that down to find some element with Selenium.
I already saw many questions and answers, the main idea I found is self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
and this is what I currently have in my code. But this is not good enough since this code is scrolling down only so this fails to find the element in case it is located in the upper part of the rollable view.
So I need a script that first scrolls up (page Up?) and after that begins scrolling down.
I tried something like this
self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
self.web_driver.execute_script("window.scrollTo(0, -document.body.scrollHeight);")
self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
但这不会向上滚动:(
but this doesn't scroll up :(
推荐答案
您可以尝试以下代码向上滚动页面:
You can try below code to scroll page up:
from selenium.webdriver.common.keys import Keys
self.web_driver.find_element_by_tag_name('body').send_keys(Keys.HOME)
另一种方式(首选),您可以向上滚动到必填元素:
Another way (preferred) you can scroll up to required element:
element = self.web_driver.find_element_by_xpath('SOME_XPATH') # you can use ANY way to locate element
coordinates = element.location_once_scrolled_into_view # returns dict of X, Y coordinates
self.web_driver.execute_script('window.scrollTo({}, {});'.format(coordinates['x'], coordinates['y']))
这篇关于上下滚动以使用Selenium Python将Element引入视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!