問題描述
您好,我想知道如何使用 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 點擊隱藏元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!