本示例所需jar包:
jdk1.8
selenium-3.5.0
FireFox 55.0.2
geckodriver-v0.19.0-win64.zip(FireFox驱动)
(上述版本一定要对应)
1.执行网页中的js(也可以执行自己写的js代码)
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","E:\\Java\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "D:\\Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://127.0.0.1:8020/ajax/select.html");
//调用网页中的js
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("js()");
driver.close();
}
网页源码
<script type="text/javascript">
$(function(){
document.getElementById('sl').value='yx'
});
function js(){
alert(document.getElementById('sl').options[document.getElementById('sl').selectedIndex].text);
alert(document.getElementsByTagName("img")[0].src);
}
</script>
</head>
<body>
<select id="sl">
<option value="">请选择</option>
<option value="bmj">张三</option>
<option value="lzd">李四</option>
<option value="yx">王五</option>
<option value="gy">赵六</option>
</select><br />
<button οnclick="js()">select</button>
</body>
1.调用js篡改网页内容
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","E:\\Java\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "D:\\Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
//调用js(篡改百度的log图片)
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByTagName('img')[0].src='http://img.mmjpg.com/2015/118/7.jpg'");
//driver.close();
}