Clicking Elements in Selenium using JavaScript – 使用JavaScript在Selenium中点击元素

最后修改: 2020年 5月 19日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’re going to take a look at a simple example of how to click and element in Selenium WebDriver using JavaScript.

在这个简短的教程中,我们将看一个简单的例子,即如何在SeleniumWebDriver中使用JavaScript来点击和元素。

For our demo, we’ll use JUnit and Selenium to open https://baeldung.com and search for “Selenium” articles.

在我们的演示中,我们将使用JUnit和Selenium来打开https://baeldung.com 并搜索 “Selenium “文章。

2. Dependencies

2.依赖性

First, we add the selenium-java and junit dependencies to our project in the pom.xml:

首先,我们在pom.xml中把selenium-javajunit依赖项添加到我们的项目中。

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

3. Configuration

3.配置

Next, we need to configure WebDriver. In this example, we’ll use its Chrome implementation, after downloading its latest version:

接下来,我们需要配置WebDriver。在本例中,我们将在下载其最新版本之后,使用其Chrome的实现。

@Before
public void setUp() {
    System.setProperty("webdriver.chrome.driver", new File("src/main/resources/chromedriver.mac").getAbsolutePath());
    driver = new ChromeDriver();
}

We’re using a method annotated with @Before to do the initial setup before each test. Inside we’re setting the webdriver.chrome.driver property defining the chrome driver location. After that, we’re instantiating the WebDriver object.

我们使用一个带有@Before注释的方法,在每次测试前进行初始设置。我们在里面设置webdriver.chrome.driver属性,定义chrome驱动位置。之后,我们将实例化WebDriver对象。

When the test finishes we should close the browser window. We can do it by placing the driver.close() statement in a method annotated with @After. This makes sure it’ll be executed even if the test fails:

测试结束后,我们应该关闭浏览器窗口。我们可以通过将driver.close()语句放在一个带有@After注释的方法中来实现。这样可以确保即使测试失败,它也会被执行。

@After
public void cleanUp() {
    driver.close();
}

4. Opening the Browser

4.打开浏览器

Now, we can create a test case that will do our first step – open the website:

现在,我们可以创建一个测试案例,它将完成我们的第一步–打开网站。

@Test
public void whenSearchForSeleniumArticles_thenReturnNotEmptyResults() {
    driver.get("https://baeldung.com");
    String title = driver.getTitle();
    assertEquals("Baeldung | Java, Spring and Web Development tutorials", title);
}

Here, we use the driver.get() method to load the webpage. Next, we verify its title to make sure we’re in the right place.

在这里,我们使用driver.get()方法来加载网页。接下来,我们验证其标题,以确保我们在正确的地方。

5. Clicking an Element Using JavaScript

5.使用JavaScript点击一个元素

Selenium comes with a handy WebElement#click method that invokes a click event on a given element. But in some cases click action is not possible.

Selenium带有一个方便的WebElement#click方法,可以调用一个给定元素的点击事件。但在某些情况下,点击动作是不可能的。

One example is if we want to click a disabled element. In that case, WebElement#click throws an IllegalStateException. Instead, we can use Selenium’s JavaScript support.

一个例子是,如果我们想点击一个禁用的元素。在这种情况下,WebElement#click会抛出一个IllegalStateException。相反,我们可以使用Selenium的JavaScript支持。

To do this, the first thing that we’ll need is the JavascriptExecutor. Since we are using the ChromeDriver implementation, we can simply cast it to what we need:

要做到这一点,我们首先需要的是JavascriptExecutor。由于我们使用的是ChromeDriver实现,我们可以简单地把它投到我们需要的地方。

JavascriptExecutor executor = (JavascriptExecutor) driver;

After getting the JavascriptExecutor, we can use its executeScript method. The arguments are the script itself and an array of script parameters. In our case, we invoke the click method on the first argument:

在得到JavascriptExecutor之后,我们可以使用其executeScript方法。参数是脚本本身和一个脚本参数的数组。在我们的例子中,我们在第一个参数上调用了点击方法。

executor.executeScript("arguments[0].click();", element);

Now, lets put it together into a single method that we’ll call clickElement:

现在,让我们把它整合成一个方法,我们称之为clickElement

private void clickElement(WebElement element) {
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
}

And finally, we can add this to our test:

最后,我们可以把这个添加到我们的测试中。

@Test
public void whenSearchForSeleniumArticles_thenReturnNotEmptyResults() {
    // ... load https://baeldung.com
    WebElement searchButton = driver.findElement(By.className("nav--menu_item_anchor"));
    clickElement(searchButton);

    WebElement searchInput = driver.findElement(By.id("search"));
    searchInput.sendKeys("Selenium");

    WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".btn-search"));
    clickElement(seeSearchResultsButton);
}

6. Non-Clickable Elements

6.不可点击的元素

One of the most common problems occurring while clicking an element using JavaScript is executing the click script before the element is clickable. In this situation, the click action won’t happen but the code will continue to execute.

在使用JavaScript点击元素时发生的最常见的问题之一是在元素可点击之前执行点击脚本。在这种情况下,点击动作将不会发生,但代码将继续执行。

To overcome this issue, we have to hold back the execution until the clicking is available. We can use WebDriverWait#until to wait until the button is rendered.

为了克服这个问题,我们必须暂缓执行,直到有了点击。我们可以使用WebDriverWait#until来等待,直到按钮被渲染。

First, WebDriverWait object requires two parameters; the driver and a timeout:

首先,WebDriverWait对象需要两个参数;驱动和超时。

WebDriverWait wait = new WebDriverWait(driver, 5000);

Then, we call until, giving the expected elementToBeClickable condition:

然后,我们调用until,给出预期的elementToBeClickable条件。

wait.until(ExpectedConditions.elementToBeClickable(By.className("nav--menu_item_anchor")));

And once that returns successfully, we know we can proceed:

一旦成功返回,我们知道我们可以继续进行。

WebElement searchButton = driver.findElement(By.className("nav--menu_item_anchor"));
clickElement(searchButton);

For more available condition methods refer to the official documentation.

关于更多可用的条件方法,请参考官方文档

7. Conclusion

7.结语

In this tutorial, we’ve learned how to click an element in Selenium using JavaScript. As always, the source for the article is available over on GitHub.

在本教程中,我们已经学会了如何使用JavaScript在Selenium中点击一个元素。与往常一样,本文的源代码可以在GitHub上找到