转:selenium webdriver 执行javascript代码

在用selenium webdriver 编写web页面的自动化测试代码时,可能需要执行一些javascript代码,selenium本身就支持执行js,我们在代码中import org.openqa.selenium.JavascriptExecutor;就可以使用executeScriptexecuteAsyncScript这两个方法了,其中executeScript是同步方法,用它执行js代码会阻塞主线程执行,直到js代码执行完毕;executeAsyncScript方法是异步方法,它不会阻塞主线程执行。
executeScript方法如果有返回值,有以下几种情况:

  • 如果返回一个页面元素(document element), 这个方法就会返回一个WebElement
  • 如果返回浮点数字,这个方法就返回一个double类型的数字
  • 返回非浮点数字,方法返回Long类型数字
  • 返回boolean类型,方法返回Boolean类型
  • 如果返回一个数组,方法会返回一个List<Object>
  • 其他情况,返回一个字符串
  • 如果没有返回值,此方法就会返回null

executeScript例子:

01 import java.util.concurrent.TimeUnit;
02  
03 import org.openqa.selenium.By;
04 import org.openqa.selenium.JavascriptExecutor;
05 import org.openqa.selenium.WebDriver;
06  
07 /**
08 * @author youthflies yeetrack.com
09 * Mytest.java  2013-5-19
10 * 测试所用临时文件
11 */
12 public class Mytest
13 {
14     public static void main(String[] args) throws InterruptedException
15     {
16         //可能需要设置firefox的路径
17         WebDriver driver = new FirefoxDriver();
18         try
19         {
20             driver.get("http://www.baidu.com");
21             //利用webdriver键入搜索关键字
22             //driver.findElement(By.id("kw")).sendKeys("yeetrack");
23             //利用js代码键入搜索关键字
24             ((JavascriptExecutor)driver).executeScript("document.getElementById("kw").value="yeetrack"");
25             //利用js代码取出关键字
26             String keyword = (String) ((JavascriptExecutor)driver).executeScript("var input = document.getElementById("kw").value;return input");
27             System.out.println(keyword);
28             driver.findElement(By.id("su")).click();
29             TimeUnit.SECONDS.sleep(5);
30          }
31         catch (Exception e)
32         {
33             e.printStackTrace();
34         }
35         finally
36         {
37             driver.quit();
38         }
39  }
40  
41 }

executeAsyncScript是异步地执行js,可以用来发送ajax请求,详细参见官方文档:http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/JavascriptExecutor.htmlhttp://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html

原文地址:https://www.cnblogs.com/lci05/p/3831496.html