使用webdriver滚动到元素?

Sid*_*Sid 52 python selenium python-3.x selenium-webdriver

我仍然在学习并回答我的一个问题:在这里,我被告知它可能是因为有问题的元素不在视野中.

我查看了文档,所以这里是最相关的答案:这里

您可以使用"org.openqa.selenium.interactions.Actions"类移动到元素:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
## actions.click();
actions.perform();
Run Code Online (Sandbox Code Playgroud)

当我尝试使用上面的内容滚动到元素时:它说WebElement没有定义.

我想这是因为我没有导入相关模块.有人可以指出我应该导入的内容吗?

编辑:正如alecxe所指出的,这是java代码.

但与此同时,在试图弄清楚它一段时间之后.我找到了WebElement的导入方法:

from selenium.webdriver.remote.webelement import WebElement
Run Code Online (Sandbox Code Playgroud)

可能会帮助像我这样的人.

如何,这也是一个很好的教训,IMO:

去:文档

class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False)
Run Code Online (Sandbox Code Playgroud)

需要分成上面提到的命令格式.

ale*_*cxe 95

您正在尝试使用Python运行Java代码.在Python/Selenium中,org.openqa.selenium.interactions.Actions它们反映在ActionChains类中:

from selenium.webdriver.common.action_chains import ActionChains

element = driver.find_element_by_id("my-id")

actions = ActionChains(driver)
actions.move_to_element(element).perform()
Run Code Online (Sandbox Code Playgroud)

或者,您也可以通过以下方式"滚动到视图" scrollIntoView():

driver.execute_script("arguments[0].scrollIntoView();", element)
Run Code Online (Sandbox Code Playgroud)

如果您对这些差异感兴趣:

  • 当我按照您的建议调用move_to时,出现了selenium.common.exceptions.MoveTargetOutOfBoundsException:消息:(164,1297)超出了视口的宽度(1366)和高度(694)。我很感谢您的回答,我认为这是解决问题的方法(而且我已经从您的回答中学到了ActionChains),但是看起来它需要一些改进。谢谢1 (2认同)

And*_*son 39

它不是问题的直接答案(它不是关于Actions),但它也允许您轻松滚动到所需的元素:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view
Run Code Online (Sandbox Code Playgroud)

这实际上打算返回页面上元素的坐标(x,y),但也向右向下滚动到目标元素

  • 首先我添加了`()`后面,并且错误''dict'对象不可调用',我检查了元素类型是`WebElement`.然后我删除了`()`并且工作了.这不是一种方法吗?我的意思是,为什么没有`()`需要? (2认同)

Nei*_*ski 8

除了move_to_element()scrollIntoView()我想提出以下的代码的企图居中的元件在视图中:

desired_y = (element.size['height'] / 2) + element.location['y']
window_h = driver.execute_script('return window.innerHeight')
window_y = driver.execute_script('return window.pageYOffset')
current_y = (window_h / 2) + window_y
scroll_y_by = desired_y - current_y

driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by)
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的解决方案,尝试了其他方法,但元素不可点击。有时滚动不够,元素位于底部的“聊天框”下方,其他代码太多滚动元素位于下方的顶部。菜单 (2认同)

vit*_*iis 8

例子:

driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))
Run Code Online (Sandbox Code Playgroud)

对于任何类型的选择器,这个总是适合我。还有 Actions 类,但对于这种情况,它不是那么可靠。