如何强制 Selenium WebDriver 单击当前不可见的元素? [英] How to force Selenium WebDriver to click on element which is not currently visible?

查看:39
本文介绍了如何强制 Selenium WebDriver 单击当前不可见的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 FirefoxDriver 中使用 Selenium 2 Java API.当我填写表单时,复选框会根据表单输入添加到页面中.

I am using Selenium 2 Java API with FirefoxDriver. When I fill a form, checkboxes are added to the page depending the forms inputs.

我想使用 Selenium 模拟点击这些复选框.该元素在常规浏览器中可见且可用,但 selenium 断言这些元素不可见.

I'd like to simulate a click on those checkboxes using Selenium. The element are visible and usable in a regular browser but, selenium asserts that the elements are not visible.

"Element is not currently visible and so may not be interacted with"

我可以强制 selenium 忽略元素的不可见状态吗?如何强制 Selenium 与不可见元素交互?

Can I force selenium to ignore the non-visible state of the elements? How can I force Selenium to interact with the non-visible element?

推荐答案

Selenium 根据以下标准确定元素是否可见(使用 DOM 检查器来确定哪些 css 适用于您的元素,确保您查看计算样式):

Selenium determines an element is visible or not by the following criteria (use a DOM inspector to determine what css applies to your element, make sure you look at computed style):

  • 可见性 != 隐藏
  • display != none(也针对每个父元素进行检查)
  • opacity != 0(点击元素时不检查)
  • 高度和宽度都 > 0
  • 对于输入,属性类型 != hidden

您的元素符合这些条件之一.如果您无法更改元素的样式,您可以通过以下方式使用 javascript 强制执行此操作(因为您说的是 Selenium2 API,所以假设使用 WebDriver):

Your element is matching one of those criteria. If you do not have the ability to change the styling of the element, here is how you can forcefully do it with javascript (going to assume WebDriver since you said Selenium2 API):

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", inputElement);

但这不会触发 javascript 事件,如果您依赖于该输入的更改事件,您也必须触发它(有很多方法可以做到,最容易使用该页面上加载的任何 javascript 库).

But that won't fire a javascript event, if you depend on the change event for that input you'll have to fire it too (many ways to do that, easiest to use whatever javascript library is loaded on that page).

可见性检查的来源 -

https://github.com/SeleniumHQ/selenium/blob/master/javascript/atoms/dom.js#L577

定义这个的 WebDriver 规范 -

The WebDriver spec that defines this -

https://dvcs.w3.org/hg/webdriver/raw-file/tip/webdriver-spec.html#widl-WebElement-isDisplayed-boolean

这篇关于如何强制 Selenium WebDriver 单击当前不可见的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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