【问题标题】:Selenium webdriver. Endless page loading硒网络驱动程序。无休止的页面加载
【发布时间】:2015-07-02 14:58:28
【问题描述】:

我使用 Selenium webdriver 和 Firefox 来抓取网页。有时,网络浏览器会无限期地等待一些过多的请求完成(例如对 facebook.net)。

我尝试使用 BrowserMob-Proxy 过滤这些请求。但这没有帮助。这些请求,即使在收到 200 或 404 代码后,也不会停止。

我考虑过一段时间后停止 Web 浏览器加载页面的可能性。 例如:

try {
    Thread.sleep(5000);
} catch (InterruptedException ex) {
      Thread.currentThread().interrupt(); }
((JavascriptExecutor) driver).executeScript("window.stop();");

但在网页完全加载之前它不起作用。

在我的情况下,你能建议我做什么?

附:这是使用 pageLoadTimeout 参数的代码。

WebDriver driver;
FirefoxBinary firefox;
FirefoxProfile customProfile;

public static void main(String[] args) {
openFirefox();
for (String url : listOfUrls) {                   
  Boolean pageLoaded = false;
  while (pageLoaded == false) {
  try {
    driver.get(url);
    pageLoaded = true;
    } catch (org.openqa.selenium.TimeoutException ex) {
      System.out.println("Got TimeoutException on page load. Restarting browser...");
      restartFirefox();
    }
  }
  //here I do something with a content of a webpage
 }
 }

 public static void openFirefox(){
        firefox = new FirefoxBinary(new File(Constants.PATH_TO_FIREFOX_EXE));
        customProfile = new FirefoxProfile();
        customProfile.setAcceptUntrustedCertificates(true);
        customProfile.setPreference("webdriver.load.strategy", "unstable");
        driver = new FirefoxDriver(firefox, customProfile);
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
    } 

private static void restartFirefox() {
        driver.close();
        firefox.quit();
        openFirefox();
    }

【问题讨论】:

标签: java selenium browsermob-proxy


【解决方案1】:
  1. 如何使用超时?因此,对于您正在使用的每个 WebDriver 实例,您需要设置:

    WebDriver.Timeouts pageLoadTimeout(long time, java.util.concurrent.TimeUnit unit)

Documentation:

设置等待页面加载完成之前的时间量 抛出错误。如果超时为负,页面加载可以 无限期。

Parameters:
time - The timeout value.
unit - The unit of time. Returns:
A Timeouts interface.
  1. 我尝试使用 BrowserMob-Proxy 过滤这些请求。但它 没有帮助。这些请求,即使在收到 200 或 404 代码后, 不会停止。

“没有帮助”是什么意思。我不相信你。请分享您将 URL 列入黑名单的代码。例如,以下代码为我返回了任何 google-analytics 相关网站的 HTTP.200

server.blacklistRequests("https?://.*\\.google-analytics\\.com/.*", 200); // server is bmp proxy server
  1. 我听说WebDriver 现在应该有webdriver.load.strategy。我从来没有使用过它。所以 WebDrivers 阻塞调用 (a'la get()) 的默认行为是等待 document.readyState 变为 complete,但我已经读过使用此属性可以告诉驱动程序立即返回。所以可能值得用谷歌搜索一段时间。

【讨论】:

  • 对不起,长时间的沉默。不幸的是,我无法分享我使用 BrowserMob 的代码,因为我已经删除了它。不幸的是,您的 1 和 3 选项不起作用。有时我会在 1 分钟延迟后得到 TimeOut Exception,但有时我没有得到它,而且我的 Web 浏览器通常会无休止地等待一些后台请求。我在 P.S. 的顶部添加了使用 pageLoadTimeout 和 readyState 的代码。块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2021-11-01
相关资源
最近更新 更多