WebDriver拾级而上·之十三 调用Java Script

在用selenium 1.X的时候常常会用到geteval_r()方法来执行一段js脚本来对页面进行处理。
然selenium webdriver也提供这样的一个方法: JavascriptExecutor. executeScript(string)
例如:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

public class   SimpleExample {     
       public static void main(String[] args) {
              ChromeDriver driver = new ChromeDriver();
driver.executeAsyncScript( "arguments[0](); alert('Hello')" );
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.switchTo().alert().accept();
       }
}

上面是一个最简单的例子,打开一个浏览器,然后弹层一个alert框。注意这里的driver要被强制转换成JavascriptExecutor。

下面演示在打开51.com首页如何得到帐号输入框中显示的字符,并打印输出。
WebDriver拾级而上路之十三 <wbr>调用Java <wbr>Script


package com.test;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Test_JsExecutor {
public static void main(String[] args) {
String url = "http://www.51.com";
//打开chrome
WebDriver dr = new ChromeDriver();
String js = "var user_input = document.getElementByIdx_x_x_x(\"passport_51_user\").title;return user_input;";
String title =  (String)((JavascriptExecutor)dr).executeScript( js);
System.out.println(title);

        dr.quit();
}
}
输出结果为:用户名/彩虹号/邮箱

其他用例:
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("(function(){
                                    inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','"
                                                      + fieldName + "','"+ value + "');
                                  }
                        )()"
                      );

你可能感兴趣的:(自动化测试+Selenium)