Selenium WebDriver点击隐藏元素 [英] Selenium WebDriver clicking on hidden element
问题描述
您好我想知道如何使用Selenium WebDriver点击隐藏元素和/或禁用元素。
Hi I would like to know how to click on hidden element and/or disable element by using Selenium WebDriver.
我知道selenium 1我可以这样做:
I know with selenium 1 I can do this as below:
selenium.click(id="idOfHiddenField");
这可行,但是对于selenium 2(WebDriver),这不行。我不想使用jquery来启用或显示隐藏字段或JavaScript。这是因为大多数测试都是使用xpath。
and this would work, but with selenium 2 (WebDriver), this doesn't. I do not want to use jquery to enable or show hidden fields , or JavaScript. This is because most of the test are using xpath.
或者我是否只需要使用旧的selenium来点击隐藏的字段?
Or do I just have to stay with old selenium which allows you to click on hidden fields?
推荐答案
使用 JavascriptExecutor
可以更轻松地解决问题。
There is a easier way to work around the problem using JavascriptExecutor
.
例如:
document.getElementsByClassName('post-tag')[0].click();
上面的javascript会点击此页面右上角的Selenium标签(旁边你的问题),即使它被隐藏(假设)。
The above javascript would click on the "Selenium" tag on the top right of this page (next to your question), even if it were hidden (hypothetically).
您需要做的就是通过 JavascriptExecutor
界面发出此JS指令,如下所示:
All you need to do is issue this JS instruction via the JavascriptExecutor
interface like so:
(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-tag')[0].click();");
这将使用JS沙箱和合成点击事件来执行点击操作。虽然它违背了WebDriver用户活动模拟的目的,但您可以在特殊情况下使用它,例如在您的情况下效果良好。
This would use the JS sandbox and synthetic click event to perform the click action. Although it defeats the purpose of WebDriver user activity simulation, you can use it in niche scenarios like in your case to good effect.
这篇关于Selenium WebDriver点击隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!