Selenium+Webdriver學習(三) 執行JS指令碼
阿新 • • 發佈:2019-02-15
在用selenium 1.X的時候常常會用到getEval()方法來執行一段js指令碼來對頁面進行處理,以處理一些遇到的問題。當然selenium webdriver也提供這樣的一個方法:executeScript()
下面演示在開啟51.com首頁如何得到帳號輸入框中顯示的字元,並列印輸出。
[java] view plaincopyprint?- /*** 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;
- publicclass Execu_JS {
- publicstaticvoid main(String[] args) {
- // TODO Auto-generated method stub
- WebDriver driver=new FirefoxDriver();
- driver.get("http://www.51.com");
- /** Selenium 執行JS*/
- String js =
- 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);
}
}
結果如下: