When selenium 1.x is used, the getEval () method is often used to execute a js script to process the page to deal with some problems encountered. Of course, selenium webdriver also provides the following method: executeScript ()
The following shows how to obtain the characters displayed in the account input box on the 51.com homepage and print the output.
/*** 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 stubWebDriver driver = new FirefoxDriver (); driver. get ("http://www.51.com");/** Selenium Run JS */String js = "var user_input = document. getElementById (\ "passport_51_user \"). title; return user_input; "; String input_title=(string(((javascriptexecutor?driver=.exe cuteScript (js); System. out. println ("--- input title ---" + input_title); String title = driver. getTitle (); // get the current page url String currentUrl = driver. getCurrentUrl (); // output title and currenturl System. out. println ("page title:" + title + "\ n" + "current URL" + cu RrentUrl); // (javascriptexecutor=driver=.exe cuteScript ("alert (\" hello, this is a alert! \ ")"); String when whandle = driver. getWindowHandle (); // return the current browser's window handle System. out. println ("current window handle:" + export whandle + "\ n" + export whandle); // String export whandles = driver. getWindowHandles (Set
); // Return the window handle of all browsers // String pageSource = driver. getPageSource (); // return the source code of the current page // System. out. println (pageSource + "\ n" + pageSource );}}
The result is as follows: