使用 webdriver 滚动到元素? [英] Scrolling to element using webdriver?

查看:29
本文介绍了使用 webdriver 滚动到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习并回答我的一个问题:此处,有人告诉我它可能到期了,因为相关元素不在视图中.

I am still learning and in response to one of my questions: here, I was told to that it might be due because the element in question is not in view.

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

I looked through the documentation and SO, here was the most relevant answer: here

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

You can use the "org.openqa.selenium.interactions.Actions" class to move to an element:

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

当我尝试使用上述内容滚动到元素时:它说未定义 WebElement.

When I try to use the above to scroll to the element: It says WebElement not defined.

我认为这是因为我没有导入相关模块.有人可以指出我应该导入什么吗?

I think this is because I have not imported the relevant module. Can someone point out what I am supposed to import?

正如 alecxe 指出的,这是 java 代码.

As pointed out by alecxe, this was java code.

但与此同时,在尝试弄明白了一段时间之后.我已经找到了 WebElement 的导入方法:

But in the meantime right after trying to figure it out for some time. I have found out the import method for WebElement:

from selenium.webdriver.remote.webelement import WebElement

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

Might help someone like me.

它的方法也是一个很好的教训,IMO:

The how of it is also a good lesson, IMO:

前往:文档

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

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

Need to be separated into the command form mentioned above.

推荐答案

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

You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains 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()

或者,您也可以通过 <代码>scrollIntoView():

Or, you can also "scroll into view" via scrollIntoView():

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

如果您对差异感兴趣:

这篇关于使用 webdriver 滚动到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆