如何使用 JavaScript 单击 Selenium WebDriver 中的元素?
我有以下 HTML:
<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>
我的以下用于单击Google 搜索"按钮的代码在 WebDriver 中使用 Java 运行良好.
My following code for clicking "Google Search" button is working well using Java in WebDriver.
driver.findElement(By.id("gbqfb")).click();
我想在 WebDriver 中使用 JavaScript 来单击按钮.我该怎么做?
I want to use JavaScript with WebDriver to click the button. How can I do it?
通过 JavaScript 执行点击有一些您应该注意的行为.例如,如果绑定到元素的 onclick
事件的代码调用了 window.alert()
,您可能会发现 Selenium 代码挂起,这取决于浏览器的实现司机.也就是说,您可以使用 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
接口的 click()
方法可能会更好,但是 禁用本机事件,然后再实例化您的驱动程序.这将实现相同的目标(具有相同的潜在限制),但不会强迫您编写和维护自己的 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.