selenium 对于网络延时怎么处理?

本文探讨在自动化测试和网络爬虫中遇到网络延时问题时,如何应对NoSuchElementException和TimeoutException异常。建议使用WebDriverWait类进行代码控制,或者自定义解决方案。
摘要由CSDN通过智能技术生成

在自动化测试或网络爬虫运行时,经常会用到网络状况不好的情况,那么之前写的代码就经常会出现异常,比如 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;
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值