如何在WebdriverIO中控制PhantomJS以跳过下载/加载某种资源(即字体,图像,css,js)?

时间:2016-02-19 13:27:00

标签: node.js selenium-webdriver phantomjs ghostdriver webdriver-io

下面是我的代码,目前这工作正常..但我想优化它不加载/下载一些资源,如(字体,图像,CSS,js)..我已经读过api文档,但我和#39;无法找到相关的配置..好吧,我使用webdriverIO和phantomjs作为浏览器..

'use strict';

var _ = require('lodash');
var webdriverio = require('webdriverio');
var cheerio = require('cheerio');

/**
 * Base class for browser based crawler.
 * To run this crawler you need to first run phantomJS with webdriver on localhost
 * ```
 * ./phantomjs --webdriver 4444
 * ```
 */
class BaseWebdriverIO {
  /**
   * Constructor
   * @param opts - webdriverio config http://webdriver.io/guide/getstarted/configuration.html
   */
  constructor(opts) {
    this.opts = _.defaults(opts || {}, {
      desiredCapabilities: {
        browserName: 'phantomjs'
      }
    });
  }

  /**
   * webdriver and parse url func
   * @param parseUrl
   * @returns {Promise}
   */
  parse(parseUrl) {
    console.log("getting url", parseUrl);

    return webdriverio.remote(this.opts)
      .init()
      .url(parseUrl)
      .waitForVisible('body')
      .getHTML('body', false, function(err, html) {
        if (err) {
          throw new Error(err);
        }

        this.end();
        return cheerio.load(html);
      });
  }
}

module.exports = BaseWebdriverIO;

我无法找到与此相关的任何文档。 谁能告诉我,我怎么能这样做?

修改/更新:我找到了一个工作示例,可以使用此处的phantomjs.cli.args设置来优化无法加载的图片:https://github.com/angular/protractor/issues/150#issuecomment-128109354一些基本设置已经过配置和工作正常,这是修改后的desiredCapabilities设置对象:

desiredCapabilities: {
        'browserName': 'phantomjs',
        'phantomjs.binary.path': require('phantomjs').path,
        'phantomjs.cli.args': [
          '--ignore-ssl-errors=true',
          '--ssl-protocol=any', // tlsv1
          '--web-security=false',
          '--load-images=false',
          //'--debug=false',
          //'--webdriver-logfile=webdriver.log',
          //'--webdriver-loglevel=DEBUG',
        ],
        javascriptEnabled: false,
        logLevel: 'verbose'
}

css / fonts optimization我在堆栈溢出How can I control PhantomJS to skip download some kind of resource?上发现了问题,并且讨论的解决方案是这样的:

page.onResourceRequested = function(requestData, request) {
    if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData['Content-Type'] == 'text/css') {
        console.log('The url of the request is matching. Aborting: ' + requestData['url']);
        // request.abort(); 
        request.cancel(); 
    }
};

但是我无法通过webdriverIO的配置desiredCapabilities对象触发此功能,即onResourceRequested() ..

有谁能告诉我如何在我的WebdriverIO脚本功能中以任何方式调用/定义此函数?感谢。

0 个答案:

没有答案