Use the JavaScriptExecutor object to implement the click action of the page element. This method is mainly used to solve in some cases, the .click() method of page elements cannot take effect.
Tested page: http://www.baidu.com
The example code is as follows:
package cn.om.webdriverapi; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; public class TestClickButtonWithJS { // Use the JavaScriptExecutor object to implement the page click action. Mainly used in some cases, the click() method of the page element cannot take effect WebDriver driver; String baseURL; JavascriptExecutor jsexecutor; @BeforeMethod public void beforeMethod() { baseURL = "http://www.baidu.com"; System.setProperty("webdriver.firefox.bin", "E:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(); driver.get (baseURL); } @AfterMethod public void afterMethod() { driver.quit(); } @Test public void testClickButtonWithJavaScript() { //find search button WebElement but = driver.findElement(By.id("su")); WebElement input = driver.findElement(By.id("kw")); input.sendKeys("Use JavaScript statements to click on page elements"); JavaScriptClick(but); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace (); } } public void JavaScriptClick(WebElement element) { jsexecutor = (JavascriptExecutor) driver; try { // Determine whether the incoming element element is in a clickable state and whether it can be displayed on the page if (element.isEnabled() && element.isDisplayed()) { System.out.println("Click on page element using JavaScript"); // Execute the JavaScript statement arguments[0].click(); //arguments[0] represents the first parameter, which is element jsexecutor.executeScript("arguments[0].click();", element); } else { System.out.println("The element on the page cannot be clicked"); } } catch (StaleElementReferenceException e) { // TODO: handle exception System.out.println("The page element is not attached to the page"+e.getStackTrace()); } catch (NoSuchElementException e) { // TODO: handle exception System.out.println("The element to be manipulated was not found in the page"+e.getStackTrace()); } catch (Exception e) { // TODO: handle exception System.out.println("Unable to complete the click action"+e.getStackTrace()); } } }