selenium定位元素,合理设置等待时间
selenium定位元素,有时需要设置等待时间,但是时间不定,可以按照依次递增等待时间的方式,设置等待,大体代码如下
package util;
import java.util.List;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ElementLocateHelper {
private static WebDriver driver = null;
private static Logger logger = ConfigHelper.logger;
static {
System.setProperty("webdriver.firefox.bin", ConfigHelper.getObject("FIREFOX_PATH"));
driver = new FirefoxDriver();
}
public static void setWebDriver(WebDriver driver){
ElementLocateHelper.driver = driver;
}
public static WebDriver getWebDriver(){
return ElementLocateHelper.driver;
}
//查找页面元素
public static WebElement FindWebElement(String elementLocation) throws InterruptedException{
boolean flag = false;
int count = 10;
while(!flag){
try{
driver.findElement(By.xpath(elementLocation));
flag = true;
}catch(org.openqa.selenium.NoSuchElementException e){
Thread.sleep(500+count*100);
count--;
if(count == 0){
logger.warn(elementLocation +"is not exist!");
flag =true;
return null;
}
}
}
return driver.findElement(By.xpath(elementLocation));
}
//查找页面元素,并且点击
public static void FindWebElementAndClick(String elementLocation) throws InterruptedException{
boolean flag = false;
int count = 10;
while(!flag){
try{
driver.findElement(By.xpath(elementLocation)).click();
flag = true;
}catch(org.openqa.selenium.NoSuchElementException e){
Thread.sleep(500+count*100);
count--;
if(count == 0){
logger.warn(elementLocation +"is not exist!");
flag =true;
}
}
}
}
//click2暂时没用
public static void FindWebElementAndClick2(String elementLocation)throws InterruptedException {
boolean flag = false;
int count = 10;
while(!flag){
try{
driver.findElement(By.cssSelector(elementLocation)).click();
flag = true;
}catch(org.openqa.selenium.NoSuchElementException e){
Thread.sleep(500+count*100);
count--;
if(count == 0){
logger.warn(elementLocation +"is not exist!");
flag =true;
}
}
}
}
//查找页面元素,并且发送内容
public static void FindWebElementAndSendKeys(String elementLocation, String elementKey) throws InterruptedException{
boolean flag = false;
int count = 10;
while(!flag){
try{
driver.findElement(By.xpath(elementLocation)).sendKeys(elementKey);
flag = true;
}catch(org.openqa.selenium.NoSuchElementException e){
Thread.sleep(500+count*100);
count--;
if(count == 0){
logger.warn(elementLocation +"is not exist!");
flag =true;
}
}
}
}
}
注:当然,可以设置一个Thread.sleep(XXX),XXX固定的时间,视情况而定