使用BrowserMobProxy配置WebDriverIO

Configure WebDriverIO with BrowserMobProxy

本文关键字:WebDriverIO 配置 BrowserMobProxy 使用      更新时间:2023-09-26

有人有关于如何使用WebDriverIO配置BrowserMobProxy的正确示例吗?这样我就可以捕获网络流量。我以前使用过WebDriverJS,它本质上是WebDriverIO的一个不推荐使用的版本。

您可以使用以下代码来完成此操作。确保您的browsermob proxyselenium server正在运行。然后将下面的代码复制粘贴到test.js文件中,并将其放在webdriverio安装的文件夹中。从cmd转到该文件夹并运行node test.js。应该在test.js所在的位置生成stuff.har

var Proxy = require('browsermob-proxy').Proxy
    , webdriverio = require("./node_modules/webdriverio/")
    , fs = require('fs')
    , proxy = new Proxy()
;
proxy.cbHAR('search.yahoo.com', doSeleniumStuff, function(err, data) {
        if (err) {
            console.error('ERR: ' + err);
        } else {
            fs.writeFileSync('stuff.har', data, 'utf8');

        }
});
function doSeleniumStuff(proxy, cb) {
    var browser = webdriverio.remote({
        host: 'localhost'
        , port: 4444
        , desiredCapabilities: { browserName: 'firefox', seleniumProtocol: 'WebDriver', proxy: { httpProxy: proxy } }
    });
    browser
        .init()
        .url("http://search.yahoo.com")
        .setValue("#yschsp", "javascript")
        .submitForm("#sf")
        .end().then(cb);        
}

如果你只想捕获网络流量,那么还有一种方法可以做到。

Webdriverio允许您使用Chrome开发工具协议。

请阅读webdriverio博客

这是关于如何将chrome-dev工具与webdriverio一起使用的示例之一,如果您需要更多帮助,请告诉我。

const { remote } = require('webdriverio')
    let browser;
    (async () => {
        browser = await remote({
            automationProtocol: 'devtools',
            capabilities: {
                browserName: 'chrome'
            }
        })
        await browser.url('https://webdriver.io')
        await browser.call(async () => {
            const puppeteerBrowser = browser.getPuppeteer()
            const page = (await puppeteerBrowser.pages())[0]
            await page.setRequestInterception(true)
            page.on('request', interceptedRequest => {
                if (interceptedRequest.url().endsWith('webdriverio.png')) {
                    return interceptedRequest.continue({
                        url: 'https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png'
                    })
                }
                interceptedRequest.continue()
            })
        })
        // continue with WebDriver commands
        await browser.refresh()
        await browser.pause(2000)
        await browser.deleteSession()
    })().catch(async (e) => {
        console.error(e)
        await browser.deleteSession()
    })

由于我在使用browsermob proxy(AFAIK)解决此问题时运气不佳

我创建了一个小的npm模块来将硒测试捕获为HAR文件-https://www.npmjs.com/package/har-recorder

我采纳了@Raulster24的建议,并使用Chrome开发工具协议实现了它https://github.com/loadmill/har-recorder/blob/master/index.js