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)
如果您对这些差异感兴趣:
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
),但也向右向下滚动到目标元素
除了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)
例子:
driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))
Run Code Online (Sandbox Code Playgroud)
对于任何类型的选择器,这个总是适合我。还有 Actions 类,但对于这种情况,它不是那么可靠。
归档时间: |
|
查看次数: |
62097 次 |
最近记录: |