使用webdriverio迭代多个URL

时间:2017-11-05 08:59:23

标签: javascript selenium-webdriver promise async-await webdriver-io

我有以下代码。但这不起作用,只创建一个名为googleScreenshot-loop-0.png的屏幕截图,该屏幕截图为白色,不显示网页。我如何迭代多个URL?

const path = require('path');
const webdriverio = require('webdriverio');

const options = {
    desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: ['--headless', '--disable-gpu', '--window-size=1920,1080'],
            binary: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
        },
    },
};
const client = webdriverio.remote(options);

const arr = ['https://domain1.com/', 'https://domain2.com/', 'https://domain3.com/'];

let i = 0;
Promise.all(arr).then((values) => {
    client
        .init()
        .url(values)
        .execute(function () {
            const styleElement = document.createElement('style');
            document.head.appendChild(styleElement);
            styleElement.sheet.insertRule('::-webkit-scrollbar { display: none; }');
        })
        .saveScreenshot(path.join(__dirname, `googleScreenshot-loop-${i++}.png`))
        .end();
}).catch((reason) => {
    console.log(reason);
});

略微修改的例子:

client.init().then(() => {
  return arr.map((value, i) => {
      return client
          .url(value)
          .execute(function () {
              const styleElement = document.createElement('style');
              document.head.appendChild(styleElement);
              styleElement.sheet.insertRule('::-webkit-scrollbar { display: none; }');
          })
          .saveScreenshot(path.join(__dirname, `googleScreenshot-loop-${i++}.png`))
  });
}).then((arrPromise) => {
  return Promise.all(arrPromise);
}).then(() => {
  return client.end();
}).catch((reason) => {
  console.log(reason);
});

这个图像创建了3个图像,但只显示了所有图像上的第一个wbesite。

更新

这个似乎有效:

const arr = ['https://domain1.com/', 'https://domain2.com/', 'https://domain3.com/'];

const init = async (array) => {
    await client.init();

    let i = 0;
    for (const value of array) {
        await client.url(value);
        await client.execute(() => {
            const styleElement = document.createElement('style');
            document.head.appendChild(styleElement);
            styleElement.sheet.insertRule('::-webkit-scrollbar { display: none; }');
        });
        await client.saveScreenshot(path.join(__dirname, `googleScreenshot-loop-${i}.png`));

        i += 1;
    }

    return client.end();
};

init(arr);

0 个答案:

没有答案