Java selenium timeout page

2019-09-09 13:39发布

问题:

I'm making an proxy checker in selenium, is there any way I can make it go onto the next proxy if it takes more then 15 seconds too load?

So, if it tries the frist proxy, it takes 15 or more seconds to load, just move onto the next proxy

package a;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.*;

public class main {

    public static void main(String[] args) throws IOException, InterruptedException {
        BufferedReader br = new BufferedReader(new FileReader("proxy.txt"));
        String line;
        BufferedWriter file = null;
        file = new BufferedWriter(new FileWriter("proxy_out.txt"));


        while ((line = br.readLine()) != null) {
            //splitting
            String str;
            str = line;
            String[] splited = line.split(":");
            //System.out.println(Arrays.toString(splited));
            String IP = splited[0];
            String PORT = splited[1];
            System.out.println(IP + ":" + PORT);


            String PROXY = IP + ":" + PORT;
            org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
            proxy.setHttpProxy(PROXY)
                    .setFtpProxy(PROXY)
                    .setSslProxy(PROXY);
            DesiredCapabilities cap = new DesiredCapabilities();
            cap.setCapability(CapabilityType.PROXY, proxy);

            WebDriver driver = new ChromeDriver(cap);


            driver.get("google.com");
            try {
                WebElement Check = driver.findElement(By.id("input_captcha"));
                if (Check.isDisplayed()) {
                    System.out.println(PROXY + " is good");
                    file.write(IP+":"+PORT);
                }
            } catch (Exception e) {
                System.out.println("Bad");

            }
            driver.close();
        }
        file.close();
    }
}

回答1:

You may try using WebDriverWait class like below.

WebDriverWait wait = new WebDriverWait(driver, 15); //Timeout is 15 seconds
WebElement element = wait.until(ExpectedConditions.elementToBeSelected(By.id("input_captcha")));

This code will continually try to find the input_captcha element, until either the element is found or the timeout is reached



回答2:

In addition to the answer provided by CARE, you can also try FluentWait. It will continuously poll for the provided condition check.

Refer different types of Selenium wait here.