Java Selenium JavaScript相关应用
程序员文章站
2022-07-14 09:46:24
...
基本应用:进入百度,弹出alert提示框
代码:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Te {
public WebDriver driver;
@Test
public void test01(){
System.setProperty("webdriver.chrome.driver", "D:\\JavaSelenium\\Driver\\chromedriver61-63\\chromedriver.exe");
driver = new ChromeDriver();
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
driver.get("https:www.baidu.com/");
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("alert('hello,world!')")
}
}
为元素赋值:进入百度,搜索框输入:hello
代码:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Te {
public WebDriver driver;
@Test
public void test01(){
System.setProperty("webdriver.chrome.driver", "D:\\JavaSelenium\\Driver\\chromedriver61-63\\chromedriver.exe");
driver = new ChromeDriver();
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
driver.get("https:www.baidu.com/");
//找到百度首页的百度一下旁边的输入框
WebElement element=driver.findElement(By.id("kw"));
JavascriptExecutor js=(JavascriptExecutor) driver;
//Javascript操作为元素赋值,适用于input,select等,其中arguments[0]代表我们的要操作的element,
//之后我们可以对我们的元素进行操作,比如赋值:"arguments[0].value='hello'",
//去除某个属性:"arguments[0].removeAttribute('readonly','readonly')"
js.executeScript("arguments[0].value='hello'",element);
}
}
去除属性:eg:readonly,有些输入框具有reonly属性,无法正常输入,我们可以去除该属性再进行输入
WebElement element=driver.findElement(By.id("***"));
JavascriptExecutor js=(JavascriptExecutor) driver;
//Javascript操作为元素赋值,适用于input,select等,其中arguments[0]代表我们的要操作的element,
//之后我们可以对我们的元素进行操作,比如赋值:"arguments[0].value='hello'",
//去除某个属性:"arguments[0].removeAttribute('readonly','readonly')"
js.executeScript("arguments[0].removeAttribute('readonly','readonly')",element);
//之后就可以正常进行输入了
element.sendKeys("hello");