使用Selenium操作JavaScript进行点击

package com.gloryroad.Demo;


import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class JavaScriptExcutor {
/**
* 解决在某些环境下,使用click方法无效的情况
*/
public WebDriver driver;
private String url="http://www.sogou.com";

@BeforeMethod
public void setUp(){
driver=new FirefoxDriver();
driver.get(url);

}


@AfterMethod
public void tearDown(){
driver.close();
}

@Test
public void testHandlerFrame(){
WebElement searchinputbox=driver.findElement(By.id("query"));
WebElement searchButton=driver.findElement(By.id("stb"));
searchinputbox.sendKeys("使用JavaScript语句进行");
JavaScriptClick(searchButton);

}
public void JavaScriptClick(WebElement element){
try {

if (element.isEnabled() && element.isDisplayed()) {

((JavascriptExecutor)driver).executeScript("arguments[0].click();",element );


}else {
System.out.println("页面上的元素无法进行点击操作");
}



} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}


}
}

你可能感兴趣的:(Java编程,测试经验总结)