selenium 对于网络延时怎么办
selenium 对于网络延时怎么处理?
在自动化测试或网络爬虫运行时,经常会用到网络状况不好的情况,那么之前写的代码就经常会出现异常,比如 NoSuchElementException或者 TimoutException 之类的。如下错误代码在网络不佳的情况下就会报错:
import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest{ public static void main(String[] args) throws InterruptedException { System.setProperty ( "webdriver.chrome.driver" , "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); try{ driver.get("http://shanghai.anjuke.com"); WebElement input=driver.findElement(By.xpath("//input[@id='glb_search0']")); input.sendKeys("selenium"); }catch(Exception e){ e.printStackTrace(); }finally{ driver.quit(); } }
如果用 WebDriverWait这个类即可对代码进行可控。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedCondition; public class NewTest{ public static void main(String[] args) throws InterruptedException { System.setProperty ( "webdriver.chrome.driver" , "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); try{ //设置页面加载超时时间为3S driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); driver.get("http://shanghai.anjuke.com"); }catch(Exception e){ //3秒后抛出异常,但程序会继续向下处理,页面也会继续加载 }finally{ //最多等待10S,每2S检查一次 WebDriverWait wait=new WebDriverWait(driver,10,2000); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { System.out.println("sleep"); return !(driver.findElements(By.xpath("//div[@id='city-panel']")).size() > 0); } }); driver.quit(); } }
如果 你觉得这段代码不好用,也可以自己写。如下:
//每2S 检查一次,但无休止地检查,直到页面加载完成为止 while(true){ if( !(driver.findElements(By.xpath("//div[@id='city-panel']")).size() > 0)) { Thread.sleep(2000); }else { break; } }