selenium webdriver ——执行javascript代码

在代码中import org.openqa.selenium.JavascriptExecutor;就可以使用executeScript、executeAsyncScript这两个方法了

executeScript是同步方法,用它执行js代码会阻塞主线程执行,直到js代码执行完毕;

executeAsyncScript方法是异步方法,它不会阻塞主线程执行。

executeScript方法如果有返回值,有以下几种情况:

如果返回一个页面元素(document element), 这个方法就会返回一个WebElement

如果返回浮点数字,这个方法就返回一个double类型的数字

返回非浮点数字,方法返回Long类型数字

返回boolean类型,方法返回Boolean类型

如果返回一个数组,方法会返回一个List<Object>

其他情况,返回一个字符串

如果没有返回值,此方法就会返回null

executeScript实例:

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
* @author Hjianhui
* JavaScript.java  2016-08-01 
* 
*/
public class testJS{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //利用webdriver键入搜索关键字
        WebDriver driver = new FirefoxDriver();
        try{
            driver.get("http://www.baidu.com");
            
            JavascriptExecutor driver_js= ((JavascriptExecutor) driver);
            //利用js代码键入搜索关键字
            driver_js.executeScript("document.getElementById(\"kw\").value=\"yeetrack\"");
//利用js代码取出关键字

        String keyword = (String)driver_js.executeScript("var input = document.getElementById(\"kw\").value; return input");

            System.out.println(keyword);    
            driver.findElement(By.id("su")).click();
        }catch (Exception e){
            e.printStackTrace();
        }
        driver.quit();    
    }
}