selenium 对于网络延时怎么处理?
2016-05-31 09:40
477 查看
在自动化测试或网络爬虫运行时,经常会用到网络状况不好的情况,那么之前写的代码就经常会出现异常,比如 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; } }
阅读更多
相关文章推荐
- [Selenium]对于某些对话框即有可能弹出来,也有可能不弹出来,这种应该怎么处理呢?
- selenium 怎么处理display:none
- 对于在多次请求之间共享信息的问题大家都是怎么处理的?
- Selenium对于对话框alert,confirm,prompt的处理
- Win10系统打开共享文件提示没有权限使用网络资源怎么处理?
- Selenium对于对话框alert,confirm,prompt的处理
- 三层网络设备对于IP报文的分片和重组处理原理
- 编写网络爬虫对于状态码的处理----HTTP常用状态码
- 网络请求时对于服务器返回NSNull对象的处理
- 京东如何处理数据中心网络对于应用性能的影响
- iOS怎么处理网络请求json中的null
- Linux2.4系列内核对于网络数据的处理
- 对于新出来的iPhone5分辨率变了该怎么处理?IOS
- 年前最后一篇----关于DOC,PDF,PPT怎么逃过网络各类文库相同文件的审核 重金悬赏高效处理大量文档的方法
- selenium python (十三)对于分页的处理
- Oracle function-based index对于数据更新处理延时问题。
- ios 对于网络图片进行的一些处理
- vSphere 5.5虚拟机网络延时故障处理
- Selenium 疑问之三:Selenium2.0 对于Wrapped元素的click()不起作用怎么办?
- 对于边界值中有不确定字符串时该怎么处理