除了通过driver操控html元素,js也在它的控制范围内,可以通过executeScript执行js语句,得到想要的动态行为。
public class Js {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "D:\\Crosscheck Browser Testing Framework\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "D:\\firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://bbs.csdn.net/");
Thread.sleep(3000);
// 执行js语句,打印网页title
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title");
System.out.println(title);
//滚动条到最下方
js.executeScript("window.scroll(0,document.body.scrollHeight)");
Thread.sleep(3000);
//滚动条到指定元素的位置
js.executeScript("arguments[0].scrollIntoView()",driver.findElement(By.linkText("博客")));
Thread.sleep(3000);
// 滚动条到指定元素的位置
js.executeScript("window.scrollBy(0,500)");
Thread.sleep(3000);
// 改变元素属性
WebElement search = driver.findElement(By.id("toolber-keyword"));
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2]);",search,"value", "hello");
Thread.sleep(3000);
driver.quit();
}
当使用click方法没有效果,又不报错时可以尝试使用js的click。
ebElement login_link=driver.findElement(By.linkText("登录"));
if(login_link.isDisplayed()&&login_link.isEnabled()) {
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("arguments[0].click();",login_link);