如何点击使用JavaScript中硒的webdriver元素 [英] How to click an element in Selenium WebDriver using JavaScript

查看:126
本文介绍了如何点击使用JavaScript中硒的webdriver元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML:

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

我的下code,请点击谷歌搜索按钮,运作良好的webdriver中使用Java。

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

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

我想用的JavaScript 与webdriver的点击按钮。我该怎么办呢?

I want to use JavaScript with WebDriver to click the button. How can I do it?

推荐答案

通过JavaScript执行一个点击都有一些行为,其中你应该知道。如果,例如,code绑定到的onclick 你的元素调用的事件 window.alert() ,你会发现你硒code挂,这取决于浏览器驱动程序的实现。这就是说,你可以使用 JavascriptExecutor 类来做到这一点。我的解决方案不同于其他人提出的,但是,你仍然可以使用webdriver的方法来定位的元素。

Executing a click via JavaScript has some behaviors of which you should be aware. 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. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// 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);

您还应该注意的是,你可能会更好使用点击() WebElement 接口的方法,但禁用本地事件实例的驱动程序之前的。这将完成相同的目标(具有相同的潜在限制),而不是强迫你编写和维护自己的JavaScript。

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. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

这篇关于如何点击使用JavaScript中硒的webdriver元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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