Foreword
In doing web automation, some cases of selenium api can not be completed, such as the need to complete js achieved by means of a third party, such as to change the properties of certain elements of the object or some special operations, future article explains how to call a special JavaScript complete operating.
usage
- JS create an object of execution, that is JavascriptExecutor object, which is cast from a driver, that is JavascriptExecutor js = (JavascriptExecutor) driver;
- Then you can call this object js executeScript method to execute some JS, JS this statement in the form of a string to pass parameters to go in executeScript
actual case
So let's take a look at practice:
scene 1
Open the Baidu home page, and pop prompt hellow, world !, Close popup, pop console output text hellow, world!
Specific code as follows:
import org.openqa.selenium.Alert; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * selenium调用JavaScript案例 * * @author rongrong */ public class TestJavaScript { WebDriver driver; @BeforeClass public void beforeClass() { System.setProperty("webdriver.chrome.driver", "Driver / chromedriver.exe" ); Driver = new new ChromeDriver (); driver.get ( "https://www.baidu.com/" ); } / ** * Scene 1: ! open Baidu home, and tips pop hellow, world !, close the pop, pop console output text hellow, World * / @Test public void testJavaScript () { JavascriptExecutor J = (JavascriptExecutor) Driver; j.executeScript ( " Alert ( 'hellow, World!') " ); the Alert Alert = . driver.switchTo () Alert (); String text = alert.getText (); System.out.println (text); alert.accept(); } @AfterClass public void afterClass() { driver.quit(); } }
Scene 2
Open the Baidu home page, Baidu button will change MyLove
Specific code as follows:
@Test public void testChangeColor() { WebElement element = driver.findElement(By.id("su")); JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("document.getElementById('su').setAttribute('value', 'MyLove');",element); }
running result
For more call JavaScript operations, interested students can try to expand, we only initiate more needs to deal with the actual situation.