有些时候webdriver是没法操作元素或浏览器的,这时候我们可以通过javascript来进行相关的操作,昨天在群里一个朋友定位一个显示框,总是无法定位点击,或者是点击无效,这个时候就可以用javascript来操作试下。
1.javascript操作浏览器滚动条
package com.testngDemo;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Demo_Javascript {
static String baseUrl;
static WebDriver driver;
@BeforeClass
public void setup()
{
driver = new FirefoxDriver();
baseUrl = "http://www.sogou.com";
driver.manage().window().maximize();
}
@Test
public void test() throws Exception
{
driver.get(baseUrl);
scrollWebDown(driver);
Thread.sleep(5000);
scrollWebTop(driver);
Thread.sleep(5000);
}
@AfterClass
public void teardown()
{
//driver.quit();
}
//移动到底部
public static void scrollWebDown(WebDriver driver)
{
((JavascriptExecutor)driver).executeScript("document.documentElement.scrollTop=10000");
}
//移动到顶部
public static void scrollWebTop(WebDriver driver)
{
((JavascriptExecutor)driver).executeScript("document.documentElement.scrollTop=0");
}
}
2.使用javascript操作元素,修改元素属性
打开搜狗主页,它有一个更多按钮,当我们定位并点击的时候发现它是闪了一下,并没有完全下拉展示(这个问题跟群里那个朋友遇到的一模一样),我们先来看下html

一般思路我们所定位的那个元素 id="more-product",无论使用是什么方法点击它,移动鼠标到这个位置,都只会让下拉框闪一下,并且无法定位下拉框里的内容,原因是什么呢?原因在后面 href="javasript:void(0);",这段js代表什么呢,代表的是点击链接后不做任何事情,void是javascript的一个操作符,只执行()里的内容但是不刷新页面。这样无论我们怎么样操作这个元素都是没有作用的。我们可以发现当鼠标移动到这个元素,下拉框 products-box 的style会由display:none变为 display:block,从而将下拉框展示在页面上,这样我们直接通过js来操作这个下拉框。
//用javascript来试试
JavascriptExecutor js = (JavascriptExecutor)driver;
// js.executeScript("document.getElementById('products-box').style.display='block';");
//或者
WebElement proBox = driver.findElement(By.id("products-box"));
js.executeScript("arguments[0].style=arguments[1]",proBox,"display:block;");
driver.findElement(By.xpath("//*[@id='index_more_gouwu']")).click();
发现可以定位下拉框的内容了:

我们也可以修改元素属性:
public void setAttribute(WebDriver driver,WebElement element,String attributeName,String value){
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element,attributeName,value);
}
对于某些富文本或者一些特殊类型的input输入框,使用javascript给其赋值:
File file = new File("resources/text");
WebElement input =driver.findElement(By.id("xxxx");((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]",input, file.getAbsolutePath());