Software Test Exchange QQ Group: 631646987, look forward to your joining!!
Ideas:
- Referencing the jquery class library
- Change element properties with jquery code
Now to change the Baidu page attributes for example, delete the id attribute, Baidu input box and button background color changed to red
The code is as follows:
Packagecom.webdirver.test;Importorg.apache.commons.lang3.StringUtils;ImportOrg.openqa.selenium.JavascriptExecutor;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.chrome.ChromeDriver;/*** Selenium reference jquery to change page element properties * *@authorAdministrator **/ Public classLoadjquery {Private StaticWebdriver Driver; /*** Inject jquery into the current page and return the success of the load * *@return */ Public BooleanInjectjquery () {Try{String Injectjquery= "var script = document.createelement (' script ');" + "var filename = \" Http://code.jquery.com/jquery-1.10.1.min.js\ ";" + "Script.setattribute (\" type\ ", \" text/javascript\ ");" + "Script.setattribute (\" src\ ", filename);" + "if (typeof script!= ' undefined ') {" + "document.getelementsbytagname (\" head\ ") [0].appendchild (script); " + "}"; ((Javascriptexecutor) driver). Executescript (Injectjquery); Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } //determine if jquery was loaded successfullyBoolean loaded =true; String s=( String) ((javascriptexecutor) driver). Executescript ("Return typeof JQuery")); if(! Stringutils.trimtoempty (s). Equals ("function"))) Loaded=false; returnloaded; } Public Static voidMain (string[] args) {System.setproperty ("Webdriver.chrome.driver", "Chromedriver.exe"); Driver=NewChromedriver (); Driver.get ("https://www.baidu.com/"); //Delete the id attribute under the Input tabJavascriptexecutor js =(javascriptexecutor) driver; String Changedisplay= "$ (' input '). REMOVEATTR (' id ');"; Js.executescript (Changedisplay); JS=(javascriptexecutor) driver; //Change the Baidu button to redString changeinput = "$ (\" input\ "). attr (\" style\ ", \" background:red\ ");"; Js.executescript (Changeinput); }}
The results of the operation are as follows:
Selenium changing element properties with jquery