繁体   English   中英

Selenium Webdriver。 无休止的页面加载

[英]Selenium webdriver. Endless page loading

我将Selenium webdriver与Firefox配合使用来抓取网页。 有时Web浏览器会无休止地等待一些多余的请求完成(例如,到facebook.net)。

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

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

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

但是,直到网页完全加载后,它才起作用。

您可以建议我做些什么?

PS这是使用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();
    }
  1. 如何使用超时? 因此,对于您使用的每个WebDriver实例,都需要设置:

    WebDriver.Timeouts pageLoadTimeout(长时间,java.util.concurrent.TimeUnit单位)

其中由文档

设置在引发错误之前等待页面加载完成的时间。 如果超时为负,则页面加载可能不确定。

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

你的意思是“无济于事”。 我不相信你 请分享您的代码以将网址列入黑名单。 例如,以下代码对我来说与任何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 ,但是我已经读到,使用此属性可以告诉驱动程序立即返回。 因此,可能有一段时间值得一试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM