使用webdriver滚动到元素?

2024-04-26 23:07:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍在学习并回答我的一个问题:here,有人告诉我,这可能是因为有问题的元素不在视图中。

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

您可以使用“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();

当我试图使用以上内容滚动到元素时: 它说WebElement没有定义。

我想这是因为我没有导入相关模块。有人能指出我应该进口什么吗?

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

但在这段时间里,我一直在想办法。我找到了WebElement的导入方法:

from selenium.webdriver.remote.webelement import WebElement

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

如何做到这一点也是一个很好的教训,国际海事组织:

转到:Documentation 那个

class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False)

需要分成上面提到的命令形式。


Tags: 答案文档actions视图id元素hereremote
3条回答

除了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)

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

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

这实际上是想返回页面上元素的坐标(xy),但也可以向下滚动到目标元素

您正在尝试使用Python运行Java代码。在Python/Selenium中,org.openqa.selenium.interactions.Actions反映在^{} class

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()

或者,也可以通过^{}“滚动到视图中”:

driver.execute_script("arguments[0].scrollIntoView();", element)

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

相关问题 更多 >