在用selenium 1.X的时候常常会用到getEval()方法来执行一段js脚本来对页面进行处理,以处理一些遇到的问题。当然selenium webdriver也提供这样的一个方法:executeScript()
下面演示在打开51.com首页如何得到帐号输入框中显示的字符,并打印输出。
- /*** This class is about Execute javascript
- * @author annie.wang
- */
- package com.annie.test;
- import org.openqa.selenium.JavascriptExecutor;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
- public class Execu_JS {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- WebDriver driver=new FirefoxDriver();
- driver.get("http://www.51.com");
- /** Selenium 执行JS*/
- String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";
- String input_title=(String)((JavascriptExecutor)driver).executeScript(js);
- System.out.println("---input title---"+input_title);
- String title = driver.getTitle();
- //得到当前页面url
- String currentUrl = driver.getCurrentUrl();
- //输出title和currenturl
- System.out.println("页面title:"+title+"\n"+"当前URL"+currentUrl);
- // ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");
- String windowHandle=driver.getWindowHandle() ; //返回当前浏览器的窗口句柄
- System.out.println("当前窗口句柄:"+windowHandle+"\n"+windowHandle);
- //String windowHandles=driver.getWindowHandles(Set<STRING>); // 返回所有浏览器的窗口句柄
- // String pageSource=driver.getPageSource() ; //返回当前页面的源码
- // System.out.println(pageSource+"\n"+pageSource);
- }
- }
- </STRING>
/*** This class is about Execute javascript
* @author annie.wang
*/
package com.annie.test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Execu_JS {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver=new FirefoxDriver();
driver.get("http://www.51.com");
/** Selenium 执行JS*/
String js = "var user_input = document.getElementById(\"passport_51_user\").title;return user_input;";
String input_title=(String)((JavascriptExecutor)driver).executeScript(js);
System.out.println("---input title---"+input_title);
String title = driver.getTitle();
//得到当前页面url
String currentUrl = driver.getCurrentUrl();
//输出title和currenturl
System.out.println("页面title:"+title+"\n"+"当前URL"+currentUrl);
// ((JavascriptExecutor)driver).executeScript("alert(\"hello,this is a alert!\")");
String windowHandle=driver.getWindowHandle() ; //返回当前浏览器的窗口句柄
System.out.println("当前窗口句柄:"+windowHandle+"\n"+windowHandle);
//String windowHandles=driver.getWindowHandles(Set); // 返回所有浏览器的窗口句柄
// String pageSource=driver.getPageSource() ; //返回当前页面的源码
// System.out.println(pageSource+"\n"+pageSource);
}
}
结果如下: