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。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…