selenium webdriver学习(三)------------执行js脚本

在用selenium 1.X的时候常常会用到getEval()方法来执行一段js脚本来对页面进行处理,以处理一些遇到的问题。当然selenium webdriver也提供这样的一个方法:executeScript()

 

Java代码  收藏代码
  1. import org.openqa.selenium.JavascriptExecutor;  
  2. import org.openqa.selenium.WebDriver;  
  3.   
  4. public class  SimpleExample {  
  5.   
  6.       
  7.     public static void main(String[] args) {  
  8.         WebDriver driver = new FirefoxDriver();  
  9.   
  10.           ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");  
  11.     }  
  12.   
  13. }  

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

下面演示在打开51.com首页如何得到帐号输入框中显示的字符,并打印输出。

Java代码  收藏代码
  1. import org.openqa.selenium.JavascriptExecutor;  
  2. import org.openqa.selenium.WebDriver;  
  3.   
  4. public class FirstExampe {  
  5.   
  6.       
  7.     public static void main(String[] args) {  
  8.         WebDriver driver = new FirefoxDriver();  
  9.         driver.get("http://www.51.com");  
  10.         String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";  
  11.           
  12.         String title = (String)((JavascriptExecutor)driver).executeScript( js);  
  13.         System.out.println(title);  
  14.     }  
  15.   
  16. }  

 输出结果为:

Java代码  收藏代码
  1. 用户名/彩虹号/邮箱  
posted @ 2015-06-24 09:47  yye_2010  阅读(201)  评论(0编辑  收藏  举报