Java selenium - how to properly refresh a webpage

2019-07-17 23:13发布

     ChromeOptions options = new ChromeOptions();
       options.addExtensions(new File("extension_6_2_5_0.crx")); //ZenMate
       options.addExtensions(new File("extension_2_9_2_0.crx")); //AdGuard
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(options);
          driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //Timeout after 10 seconds

This is how I set my Chrome Driver

   try {
        driver.navigate().to("http://dic.naver.com/");
    }catch (TimeoutException e){
        System.out.println("Time out Exception");
        driver.navigate().refresh();
    }

This is my code.

I run it, then it catches TimeoutException as it is supposed to, but then the browser stops taking any get() or navigate().to() or refresh commands.

Starting ChromeDriver 2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9) on port 6823
Only local connections are allowed.
Jul 18, 2018 8:47:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
[1531936076.034][SEVERE]: Timed out receiving message from renderer: 4.660
[1531936076.633][SEVERE]: Timed out receiving message from renderer: -0.606
Time out Exception
[1531936090.525][SEVERE]: Timed out receiving message from renderer: 10.000
[1531936090.563][SEVERE]: Timed out receiving message from renderer: -0.057
Exception in thread "main" org.openqa.selenium.TimeoutException: timeout
  (Session info: chrome=67.0.3396.99)
  (Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.17134 x86_64) .remote.RemoteWebDriver$RemoteNavigation.refresh(RemoteWebDriver.java:856)
    at Markov.Bots.Bot_Kancolle.stay(Bot_Kancolle.java:43)
    at Markov.Scroller.main(Scroller.java:71)

Instead it throws another TimeoutException when it executes driver.navigate().refresh(); at line 43

The browser simply stops at TimeoutException, does not refresh, does not connect to new URL when I execute another driver.get()

How do I properly catch TimeoutException and reuse this browser for next URL connection???

2条回答
孤傲高冷的网名
2楼-- · 2019-07-17 23:38

May be you can stop page loading using javascript as given below after timeout exception. This may help you.

try {
        driver.navigate().to("http://dic.naver.com/");
}
catch (TimeoutException e){
        System.out.println("Time out Exception");
        ((JavascriptExecutor)driver).executeScript("window.stop();");
}
查看更多
等我变得足够好
3楼-- · 2019-07-17 23:44

You can reuse your session like this:

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
import java.awt.*;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;

public class Test {
  public static void main(String[] args) throws InterruptedException, AWTException, IOException {
    RemoteWebDriver driver = new ChromeDriver();
    HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
    URL url = executor.getAddressOfRemoteServer();
    SessionId session_id = driver.getSessionId();
    driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.SECONDS);
    try {
      driver.navigate().to("http://dic.naver.com/");
    }catch (TimeoutException e){
      System.out.println("Time out Exception");
      driver = createDriverFromSession(session_id, url);
      driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
      driver.get("https://stackoverflow.com/");
    }
  }

  public static RemoteWebDriver createDriverFromSession(final SessionId sessionId, URL command_executor){
    CommandExecutor executor = new HttpCommandExecutor(command_executor) {

      @Override
      public Response execute(Command command) throws IOException {
        Response response = null;
        if (command.getName() == "newSession") {
          response = new Response();
          response.setSessionId(sessionId.toString());
          response.setStatus(0);
          response.setValue(Collections.<String, String>emptyMap());

          try {
            Field commandCodec = null;
            commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
            commandCodec.setAccessible(true);
            commandCodec.set(this, new W3CHttpCommandCodec());

            Field responseCodec = null;
            responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
            responseCodec.setAccessible(true);
            responseCodec.set(this, new W3CHttpResponseCodec());
          } catch (NoSuchFieldException e) {
            e.printStackTrace();
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }

        } else {
          response = super.execute(command);
        }
        return response;
      }
    };

    return new RemoteWebDriver(executor, new DesiredCapabilities());
  }
}

This is a working example, which creates a driver instance and when the driver throws TimeoutException, creates a new instance(driver) with the same session. And driver manages the window from the first driver.

查看更多
登录 后发表回答