Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

java - 如何使用JavaScript单击Selenium WebDriver中的元素(How to click an element in Selenium WebDriver using JavaScript)

I have the following HTML:

(我有以下HTML:)

<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>

My following code for clicking "Google Search" button is working well using Java in WebDriver.

(我在下面的单击“Google搜索”按钮的代码在WebDriver中使用Java工作得很好。)

driver.findElement(By.id("gbqfb")).click();

I want to use JavaScript with WebDriver to click the button.

(我想在WebDriver中使用JavaScript来单击按钮。)

How can I do it?

(我该怎么做?)

  ask by Ripon Al Wasim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Executing a click via JavaScript has some behaviors of which you should be aware.

(通过JavaScript执行点击有一些您应该注意的行为。)

If, for example, the code bound to the onclick event of your element invokes window.alert() , you may find your Selenium code hanging, depending on the implementation of the browser driver.

(例如,如果绑定到元素的onclick事件的代码调用window.alert() ,则可能会发现您的Selenium代码挂起,具体取决于浏览器驱动程序的实现。)

That said, you can use the JavascriptExecutor class to do this.

(也就是说,您可以使用JavascriptExecutor类来执行此操作。)

My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

(我的解决方案与其他提议的解决方案不同,因为您仍然可以使用WebDriver方法来定位元素。)

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver.

(您还应该注意,最好使用WebElement接口的click()方法,但在实例化驱动程序之前禁用本机事件 。)

This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

(这将实现相同的目标(具有相同的潜在限制),但不会强迫您编写和维护自己的JavaScript。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...