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 staticvoid main(String[] args) { 
  8.         WebDriver driver = new FirefoxDriver(); 
  9.  
  10.           ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")"); 
  11.     } 
  12.  
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

public class  SimpleExample {

	
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();

	      ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");
	}

}

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

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

Java代码
  1. import org.openqa.selenium.JavascriptExecutor; 
  2. import org.openqa.selenium.WebDriver; 
  3.  
  4. public class FirstExampe { 

     

  1.     public staticvoid main(String[] args) { 
  2.         WebDriver driver = new FirefoxDriver(); 
  3.         driver.get("http://www.51.com"); 
  4.         String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;"
  5.          
  6.         String title = (String)((JavascriptExecutor)driver).executeScript( js); 
  7.         System.out.println(title); 
  8.     } 
  9.  
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

public class FirstExampe {

	
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("http://www.51.com");
		String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";
		
		String title = (String)((JavascriptExecutor)driver).executeScript( js);
		System.out.println(title);
	}

}

输出结果为:

Java代码
  1. 用户名/彩虹号/邮箱 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值