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例子:

package com.yeetrack.selenium;

import java.util.concurrent.TimeUnit;

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

/**
* @author youthflies yeetrack.com
* Mytest.java  2013-5-19 
* 测试所用临时文件
*/
public class Mytest
{
    public static void main(String[] args) throws InterruptedException
    {
        //可能需要设置firefox的路径
        WebDriver driver = new FirefoxDriver();
        try
        {
            driver.get("http://www.baidu.com");
            //利用webdriver键入搜索关键字
            //driver.findElement(By.id("kw")).sendKeys("yeetrack");
            //利用js代码键入搜索关键字
            ((JavascriptExecutor)driver).executeScript("document.getElementById(\"kw\").value=\"yeetrack\"");
            //利用js代码取出关键字
            String keyword = (String) ((JavascriptExecutor)driver).executeScript("var input = document.getElementById(\"kw\").value;return input");
            System.out.println(keyword);
            driver.findElement(By.id("su")).click();
            TimeUnit.SECONDS.sleep(5);
         }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            driver.quit();
        }
 }

}  

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

版权声明

本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。

© 空空博客,本文链接:https://www.yeetrack.com/?p=560