简体   繁体   中英

How to avoid opening multiple chrome windows for running multiple URLs using Selenium WebDriverJS

How do I fix this code to not have multiple instances of my browser running when am trying to parse multiple urls? Ideally I want just one browser opening and running multiple urls in it. Any help is appreciated !

I have tried instantiating the driver outside the foreach loop but it only print results for the last url then.

async function executeTask (driver, url) {
    try{
        await driver.get(url);
        let result = await AxeBuilder(driver).analyze();
        return Promise.resolve(result);
    } 
    catch(err) {
        return Promise.reject(err);
    }
}

function iterateThroughUrls(urls) {
    urls.forEach(url => {
        var driver = new WebDriver.Builder().forBrowser('firefox').build();
        executeTask(driver, url).then(result => {
            console.log(result);
        }).catch(err => {
            //handle errors
        });
    });
}

Using async / await you can run promises one after the other in a for loop.

async function executeTask (driver, url) {
    try{
        await driver.get(url);
        let result = await AxeBuilder(driver).analyze();
        return Promise.resolve(result);
    } 
    catch(err) {
        return Promise.reject(err);
    }
}

async function serializeTasks(driver, urls) {

  const results = [];

  for (const url of urls) {
    const result = await executeTask(driver, url);
    results.push(result);
  }

  return results;

}

function iterateThroughUrls(urls) {
    var driver = new WebDriver.Builder().forBrowser('firefox').build();

    serializeTasks(driver, urls)
      .then(results => console.log(results));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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