Selenium 简明教程

Selenium WebDriver - JavaScript Executor

Selenium Webdriver 用于运行 JavaScript 命令以与页面浏览器中出现的元素通信。这是在 JavaScriptExecutor 接口的帮助下完成的。有时,Selenium Webdriver 中可用的定位器无法与页面上的元素交互,在这些情况下,我们可以借助 JavaScriptExecutor 方法。

Basic Methods to Run JavaScript Commands

JavaScriptExecutor 接口中提供了多种方法。它们如下所示 −

executeScript Method

此方法用于在当前活动窗口或框架中执行 JavaScript。它是一个匿名函数,支持多种数据类型,如 WebElements、Long、String、Lists 和 Boolean。

executeAsyncScript Method

这是一种多线程方法,用于在当前活动的窗口或框架上执行各个 JavaScript 任务。它允许页面解析继续进行,优化性能并提供极佳的灵活性。此方法使异步 JavaScript 能够以最佳方式执行。

Steps to Execute the JavaScript commands

使用 JavaScriptExecutor 接口用 Selenium Webdriver 执行 JavaScript 命令的步骤如下:

Step 1 − 导入 JavaScriptExecutor 的软件包。

Step 2 − 创建引用变量 JavaScriptExecutor 接口。

Step 3 − 调用 JavaScriptExecutor 方法。

Syntax

import org.openqa.selenium.JavascriptExecutor;
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript(script, args);

Example

让我们以以下页面为例,我们在其中用 URL 打开应用程序 − Selenium Automation Practice Form

然后,获取文本: Selenium - Automation Practice Form ,和域 www.tutorialspoint.com 。接下来,我们在 Name 标记旁边的输入框中输入文本 Selenium

selenium javascript executor1

然后,我们单击 Login ,因此,我们导航到具有文本 Welcome, Login In 的新页面。然后,我们将刷新浏览器,然后分别获取文本、URL 和域 Welcome, Login InSelenium Automation Practice Formwww.tutorialspoint.com

selenium javascript executor2

代码实现

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class JavaScriptsExe {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 25 secs
      driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface.
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // launching a URL
      j.executeScript("window.location = 'https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php'");

      // getting current URL
      String url =  j.executeScript("return document.URL;").toString();
      System.out.println("Get the current URL: " + url);

      //identify text
      WebElement t = driver.findElement(By.xpath("/html/body/div/header/div[2]/h1"));

      // get text
      String text = (String) j.executeScript("return arguments[0].innerText", t);
      System.out.println("Text is: " + text);

      // getting current domain
      String domain = j.executeScript("return document.domain;").toString();
      System.out.println("Get the current domain: " + domain);

      // enter text in input box
      WebElement e = driver.findElement(By.xpath("//*[@id='name']"));
      j.executeScript("arguments[0].value='Selenium';", e);

      // get text entered
      String text1 = (String) j.executeScript("return arguments[0].value", e);
      System.out.println("Entered text is: " + text1);

      // perform click
      WebElement b = driver.findElement(By.xpath("//*[@id='collapseTwo']/div/ul/li[2]/a"));
      j.executeScript("arguments[0].click();", b);

      //identify text
      WebElement w = driver.findElement(By.xpath("//*[@id='signInForm']/h1"));

      // get text after click
      String text2 = (String) j.executeScript("return arguments[0].innerText", w);
      System.out.println("Text found after clicking is: " + text2);

      // refresh browser
      j.executeScript("history.go(0)");

      // getting current URL after browser refresh
      String url1 =  j.executeScript("return document.URL;").toString();
      System.out.println("Get the current URL after browser refresh: " + url1);

      //identify text again after refresh
      WebElement y = driver.findElement(By.xpath("//*[@id='signInForm']/h1"));

      // get text after refresh
      String text3 = (String) j.executeScript("return arguments[0].innerText", y);
      System.out.println("Text found after refresh is: " + text3);

      // getting current domain after browser refresh
      String domain1 = j.executeScript("return document.domain;").toString();
      System.out.println("Get the current domain after browser refresh: " + domain1);

      // Quit browser
      driver.quit();
   }
}
Get the current URL:
 https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php
Text is: Selenium - Automation Practice Form
Get the current domain: www.tutorialspoint.com
Entered text is: Selenium
Text found after clicking is: Welcome, Login In
Get the current URL after browser refresh:
https://www.tutorialspoint.com/selenium/practice/login.php
Text found after refresh is: Welcome, Login In
Get the current domain after browser refresh:
www.tutorialspoint.com

Process finished with exit code 0

在上面的示例中,我们启动了一个 URL,并在控制台中获取了当前 URL 和消息 - Getting the current URL: Selenium Automation Practice Form

然后分别获取文本和域,控制台中显示的消息为 - Text is: Selenium - Automation Practice FormGetting the current domain: www.tutorialspoint.com

接下来,我们在一个输入框中输入文本 Selenium,并获取其值,控制台中显示的消息为 - Entered text is: Selenium 。然后,我们单击登录链接,并在导航后获取文本,控制台中显示的消息为: Text found after clicking is: Welcome, Login In 。最后,我们刷新了页面,并获取了页面的当前 URL、文本和域,控制台中显示的消息为 - Get the current URL after browser refresh: Selenium Useful Resources

*刷新后找到的文本为: 欢迎、登录,在浏览器刷新后获取当前域: * www.tutorialspoint.com 分别。

最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。

Example - Scroll Down With JavaScriptExecutor

现在让我们讨论如何使用 scrollTo 方法向下滚动到网页底部,并获取该页面底部出现的按钮 Login ,如下图所示。scrollTo 方法采用两个参数 - 水平和垂直顶点。

selenium javascript executor3

代码实现

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class PageDownsScroll {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 12 secs
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);

      //Opening the webpage where we will perform the scroll
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // JavascriptExecutor to scrolling to page bottom
      JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
      javascriptExecutor.executeScript("window.scrollBy(0,document.body.scrollHeight)");

      // access element at page bottom after scrolling
      WebElement w = driver.findElement(By.xpath("//*[@id='practiceForm']/div[11]/input"));

      System.out.println("Verify element presence after scroll down: " + w.isDisplayed());

      // quit the browser
      driver.quit();
   }
}

Output

Verify element presence after scroll down: true

要获取有关 Selenium Webdriver 滚动操作的更多信息,请参阅链接 Selenium Webdriver Scroll Operations

Example - Create Alert with JavaScriptExecutor

让我们以以下页面为例,在其中我们将使用 JavaScriptExecutor 在网页上创建一个警报并获取文本 Tutorialspoint

selenium javascript executor4

代码实现

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class JavaScriptAlert {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface
      JavascriptExecutor j = (JavascriptExecutor) driver;

      //  create an Alert
      j.executeScript("alert('Tutorialspoint!!!');");

      // switch driver context to alert
      Alert alrt = driver.switchTo().alert();

      // Get alert text
      String s = alrt.getText();
      System.out.println("Alert text is: " + s);

      // Quit browser
      driver.quit();
   }
}

Output

Alert text is: Tutorialspoint!!!

在上面的示例中,我们创建了一个警报,并在控制台中获取了其文本,消息为 - Alert text is: Tutorialspoint!!!

Example - Select Checkbox with JavaScriptExecutor

让我们再以以下页面为例,在其中我们将使用 JavaScript Executor 选中复选框以选择 Main Level 2 选项 −

selenium javascript executor5

代码实现

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class JavaScriptHandlesCheckbox {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // Opening the webpage where we will check checkbox
      driver.get("https://www.tutorialspoint.com/selenium/practice/check-box.php");

      // identify checkbox with xpath
      WebElement chkbox = driver.findElement(By.xpath("//*[@id='c_bs_2']"));

      // check the checkbox
      j.executeScript("document.getElementById('c_bs_2').checked=true;");

      // check if checkbox is selected
      System.out.println("Checkbox is selected: " + chkbox.isSelected());

      // Quitting browser
      driver.quit();
   }
}

Output

Checkbox is selected: true

在上面的示例中,我们选中复选框,并通过控制台中的消息验证是否选中了该复选框 - Checkbox is selected: true

Conclusion

至此,我们对 Selenium Webdriver JavaScript Executor 教程的全面讲解结束。我们从描述运行 JavaScript 命令的基本方法开始,步骤执行 JavaScript 命令,以及说明如何在 Selenium Webdriver 中处理 JavaScript Executor 的示例。这使你深入了解 Selenium Webdriver JavaScript Executor。明智的做法是不断练习你学到的内容并探索其他与 Selenium 相关的知识以加深你的理解并拓宽你的视野。