学习Selenium WebDriver中的JavascriptExecutor

794 阅读4分钟

JavascriptExecutor是Selenium提供的一个接口,它提供了一个通过Selenium WebDriver执行JavaScript的机制。它提供了两种方法,如 "executeScript "和 "executeAsyncScript",在当前选定的框架、窗口或页面上运行JavaScript。在某些情况下,实际的Webdriver命令不能像预期的那样有效地工作,这就是JavaScriptExecutor出现的地方。由于JavaScriptExecutor是一个Selenium接口,因此不需要一个额外的插件或附加组件。你可以通过导入org.openqa.selenium.JavascriptExecutor包直接使用它。

为什么在Selenium中使用JavascriptExecutor?

在Selenium webDriver中使用了各种定位器,如ID、classname、CSS Selectors、Xpath等。有时这些默认的Selenium定位器可能不起作用,这时就需要用到JavaScriptExecutor。JavaScript是一种与浏览器中的HTML交互的编程语言,要在Selenium中使用这个功能,需要JavascriptExecutor。JavaScriptExecutor用于在网页上执行操作。

有时Selenium会因为运行脚本时发生的意外动作而给出不正确的结果。假设当我们打开一个网站时有一个弹出窗口。由于这个原因,Selenium无法找到我们在脚本中记录的特定元素,从而抛出一个错误或不正确的结果。例如,我们使用click()方法来点击网页上的任何元素。有时网页控件对Selenium命令的反应并不好,我们可能会面临点击()方法的问题。如前所述,为了克服这种情况,我们使用了 JavaScriptExecutor 接口。

没有必要使用Selenium WebDriver脚本编写一个单独的脚本来在浏览器中执行JavaScript。只要使用一个预定义的接口,名为Java脚本执行器'.

我们需要导入以下包来使用Java Script Executor。

import org.openqa.selenium.JavascriptExecutor;
语法
//To utilize JavascriptExecutor, create a reference for the interface and assign it to the WebDriver instance by type casting it.

JavascriptExecutor js = (JavascriptExecutor) driver;

//We have created a JavascriptExecutor reference and now we call the executeAsyncScript/executeScript methods. The syntax for executeScript is given below:
 
js.executeScript(Script,Arguments);

Script-** 要执行的JavaScriptArguments - 脚本的参数(可选),可以是空的。Returns-** 布尔、长、列表、字符串、列表、布尔、WebElement或null中的一个。

脚本可以返回值。返回的数据类型有:

  • 布尔型
  • 长型
  • 字符串
  • 列表
  • WebElement.

JavaScriptExecutor方法的介绍

Selenium中的JavaScriptExecutor提供了两个方法,通过它们我们可以在选定的窗口或当前页面上运行JavaScript。

1.executeScript

这个方法在Selenium中当前选定的窗口或框架的上下文中执行JavaScript,脚本将作为一个匿名函数的主体被执行。

2.executeAsyncScript

该方法在Selenium中当前选定的窗口或框架的上下文中执行一个异步的JavaScript片段,在这里,脚本也将作为一个匿名函数的主体被执行。executeScript和executeAsyncScript之间的主要区别是,使用executeAsyncScript调用的脚本必须使用回调函数发出执行完成的信号 ,但executeScript不是这样的。

在Selenium中可以使用JavaScriptExecutor的一些场景

1.点击一个按钮

js.executeScript("document.getElementById('enter element id').click();");

//or

js.executeScript("arguments[0].click();", cancelButton);

2.通过传递真或假的值来处理复选框

js.executeScript("document.getElementById('enter element id').checked=false;");

3.不使用sendKeys()方法在文本框中输入文本

js.executeScript("document.getElementById('some id').value='someValue';");
js.executeScript("document.getElementById('Email').value='Knoldus.com';");

4.在Selenium Webdriver中生成弹出警报窗口

js.executeScript("alert('Welcome To Knoldus');");

5.使用Javascript刷新浏览器窗口

js.executeScript("history.go(0)");

6.在Selenium中获取整个网页的内部文本

String innerText = js.executeScript(" return document.documentElement.innerText;").toString();
System.out.println(innerText);

7.获取网页的标题

String titleText =  js.executeScript("return document.title;").toString();
System.out.println(titleText);

8.获取网页的URL

String url=  js.executeScript("return document.URL;").toString();
System.out.println(url);

9.使用Javascript导航到一个不同的页面

js.executeScript("window.location = 'https://www.knoldus.com");

10.获取域名

String domainName=  js.executeScript("return document.domain;").toString();
System.out.println(domainName);

11.使用JavaScriptExecutor查找Selenium中的隐藏元素

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

12.使用Selenium对一个应用程序进行滚动操作


//Vertical scroll - down by 800  pixels
js.executeScript("window.scrollBy(0,800)");

// for scrolling till the bottom of the page we can use the code like
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
使用Selenium JavaScriptExecutor的executor executeScript的实际例子
package knoldusTestingMaterial;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class JavaScriptExecutorClassDummy {
	static WebDriver driver;
	@Test
	public static void javaScriptExeMethod(){
		System.setProperty("webdriver.gecko.driver","D://Selenium Environment//Drivers//geckodriver.exe");
		driver = new FirefoxDriver();
		driver.get("https://www.gmail.com");
		WebElement loginButton = driver.findElement(By.xpath("//*[@id='next']"));
		
		/*Syntax:
		JavascriptExecutor js = (JavascriptExecutor) driver;  
		js.executeScript(Script,Arguments);
		script - The JavaScript to execute
		Arguments - The arguments to the script.(Optional)*/

                JavascriptExecutor js = (JavascriptExecutor)driver;
                //Uncomment each scenario and find the solution

                *//to type text in Selenium WebDriver without using sendKeys() method
                js.executeScript("document.getElementById('some id').value='someValue';");
                js.executeScript("document.getElementById('Email').value='knoldus.com'")

                /*//to click a button in Selenium WebDriver using JavaScript
                //js.executeScript("arguments[0].click();", loginButton);
                //or
                js.executeScript("document.getElementById('enter your element id').click();");
                js.executeScript("document.getElementById('next').click();");*/
 
                /*//to handle checkbox
                js.executeScript("document.getElementById('enter element id').checked=false;");*/
		
		/*//to generate Alert Pop window in selenium
		js.executeScript("alert('hello world');");*/
		
		/*//to refresh browser window using Javascript 
		js.executeScript("history.go(0)");*/
		
		/*// to get innertext of the entire webpage in Selenium
		String sText =  js.executeScript("return document.documentElement.innerText;").toString();
		System.out.println(sText);*/

		/*//to get the Title of our webpage
		String sText =  js.executeScript("return document.title;").toString();
		System.out.println(sText);*/
		
		/*//to get the domain
		String sText =  js.executeScript("return document.domain;").toString();
		System.out.println(sText);*/
		
		/*//to get the URL of our webpage
		String sText =  js.executeScript("return document.URL;").toString();
		System.out.println(sText);*/
		
		/*//to perform Scroll on application using  Selenium
		//Vertical scroll - down by 100  pixels
		js.executeScript("window.scrollBy(0,100)");
		// for scrolling till the bottom of the page we can use the code like
		//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");*/
		
		/*//to navigate to different page using Javascript?
	        //Navigate to new Page
	        js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");*/
	}
}
使用executor executeAsyncScript的实际例子
package knoldusTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaScriptExecutorClass {
@Test 
public void Login() 
{ 
WebDriver driver= new FirefoxDriver(); 
JavascriptExecutor js = (JavascriptExecutor)driver;
 
//To launch a site 
driver.get("https://www.knoldus.com"); 

//To maximize the window 
driver.manage().window().maximize(); 

//To set the script timeout to 15 seconds 
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS); 

//To declare and set the start time 
long startTime = System.currentTimeMillis(); 

//Calling executeAsyncScript() method to wait for 10 seconds 
js.executeAsyncScript("window.setTimeout(argumentsarguments.length - 1], 10000);"); 

//To get the difference current time and start time 
System.out.println("Wait time: " + (System.currentTimeMillis() - startTime)); 
}
}