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

查看:76
本文介绍了如何使用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()方法可能更好,但是使用

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单击Selenium WebDriver中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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