基本应用:进入百度,弹出alert提示框
![这里写图片描述](https://img-blog.csdn.net/20180119180132892?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3VzaHVhaTE1MDgzMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
代码:
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
![这里写图片描述](https://img-blog.csdn.net/20180119182849265?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3VzaHVhaTE1MDgzMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
代码:
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属性,无法正常输入,我们可以去除该属性再进行输入
![这里写图片描述](https://img-blog.csdn.net/20180119183502959?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3VzaHVhaTE1MDgzMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
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");