Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status, and save the data to the database. However, the issue arises when running asynchronous code within a synchronous loop, causing tasks to overlap without waiting for completion.


Here is a snippet from my array


module.exports = [{ id: '1031', store: 'CANNES - LA BOCCA' },
  { id: '1009', store: 'ST ANDRÉ-LES-VERGERS' },
  { id: '1046', store: 'MARSEILLE ST MENET' },
  { id: '1071', store: 'MARIGNANE' },
  { id: '1020', store: 'IFS' },
  { id: '1032', store: 'CORMEILLES-EN-PARISIS' },
  { id: '1044', store: 'CERGY' },
  { id: '1055', store: 'HERBLAY' }];

Check out my implementation

const chromeOptions = new chrome.Options().addArguments('disable-infobars', 'headless');
      const chromeDesktop = {
        prefs: {
          profile: {
            default_content_settings: {
              images: 2,
            },
            managed_default_content_settings: {
              images: 2,
            },
          },
        },
      };
      const driver = new webdriver.Builder()
        .withCapabilities(chromeDesktop)
        .forBrowser('chrome')
        .setChromeOptions(chromeOptions)
        .build();

for (let index = 0; index < Stores.length; index++) {
  (async function getStores(index) {
    setTimeout(async () => {
      try {
        // Code snippet omitted for brevity
      } finally {
        await driver.quit()
      }
    }, 1000 * index);
  }(index));
}

I resorted to using a temporary solution of the setTimeout function, but this approach is not optimal due to various factors affecting its functionality.

I came across suggestions to utilize the map function and Promise.all() to improve efficiency. However, I am unsure how to implement this effectively without overcomplicating the code. Any guidance on utilizing Promise.all() efficiently would be greatly appreciated.

Thank you

Answer №1

const options = new Options().addArguments("disable-infobars", "headless");
const desktopSettings = {
  prefs: {
    profile: {
      default_content_settings: {
        images: 2
      },
      managed_default_content_settings: {
        images: 2
      }
    }
  }
};
const browserDriver = new Builder()
  .withCapabilities(desktopSettings)
  .forBrowser("chrome")
  .setChromeOptions(options)
  .build();

async function fetchStores(index) {
  try {
    await browserDriver.get("https://www.chronodrive.com");
    await browserDriver.manage().addCookie({
      name: "chronoShop",
      value: `"shopId=${Stores[index].id}"`
    });
    await browserDriver.get("https://www.chronodrive.com");
    await browserDriver.wait(until.elementLocated(By.id("layer-overlay")), 4000);
    await browserDriver.executeScript("document.querySelector('#layer-overlay').style.display = 'none'");
    await browserDriver.executeScript("document.querySelector('#layer-wrapper').style.visibility = 'hidden'");
    const text = await browserDriver.findElement(By.className("dispo--empty")).getText();
    if (text.length > 30) {
      const objA = {
        store: Stores[index].store,
        dispo: text,
        id: Stores[index].id,
        lastChecked: new Date()
      };
      await Store.create(objA);
      console.log(text);
    } else {
      const objB = {
        store: Stores[index].store,
        dispo: `*** No availability in ${Stores[index].store} store ***`,
        id: Stores[index].id,
        lastChecked: new Date()
      };
      await Store.create(objB);
      console.log(`*** No availability in ${Stores[index].store} store ***`);
    }
  } finally {
    await browserDriver.quit();
  }

}

(async() => {
  for (let index = 0; index < Stores.length; index++) {
    await fetchStores(index);
  }
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Error: The element <button class="btn btn-outline-light btn-icons" type="button"> cannot be brought into view due to ElementNotInteractableException

Every time I attempt to click the download button on this page, I encounter the same issue. https://data.unwomen.org/data-portal/sdg?annex=All&finic[]=SUP_1_1_IPL_P&flocat[]=478&flocat[]=174&flocat[]=818&flocat[]=504&flocat[]=729&a ...

I'm encountering an issue with the submission button in the wizard, I suspect it could be a problem

The submit button is not working on this wizard. I believe the issue lies within the JavaScript of the form wizard. When I click the submit button, nothing happens. Upon inspecting the submit button code, I found it to be like this... <a href="#finish" ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

(node:19502) UnresolvedPromiseRejectionNotification: Promise rejection not handled (rejection id: 1): TypeError: Unable to access property 'indexOf' of undefined

I successfully integrated cucumber with nightwatch.js. Here is a snippet of my package.json file: { "name": "learning-nightwatch", "version": "1.0.0", "description": "learning nightwatch", "license": "UNLICENSED", "scripts": { "nightwatch": ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

Insert text into the cursor location within Summernote using JQuery

Currently, I am working on a flutter application where I have implemented the summernote editor using JQuery. ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); String txtIsi = data.text .replaceAll("'", '\&bsol ...

Retrieving web element text using QAF

Is there a way in QAF to extract the text of a specific webelement on a webpage? In selenium, we typically use element(by.id('id')).getAttribute('value'); Could you please provide an example of how this can be accomplished in QAF? ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

Utilizing Electron's <webview> feature to display push notification count in the title

I'm currently working on a Windows app using Electron's webViewTag to integrate WhatsApp Web. While I have successfully implemented desktop toast notifications, I am curious if it is possible to display a notification count in the title bar of my ...

Display JSON array as a table using JavaScript

Looking for assistance with integrating an API that queries the Instagram API. I want to consume my API and display the Tags Search results in a table format. The JSON response structure is as follows: {"data":[{"media_count":13485788,"name":"argentina"}, ...

AngularJS Data Binding Issue - Watch cycle fails to trigger

View the JSFiddle example here: https://jsfiddle.net/pmgq00fm/1/ I am trying to achieve real-time updating of my NVD3 chart by utilizing the setInterval() function on line 39, which updates the data bound to the directive. Here is a brief overview of the ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

Determine if an element is being hovered over using jQuery

How do I determine if the cursor is hovering over an element using jQuery or JS? I attempted to use $('#id').is(':hover'), but it doesn't seem to be functioning as expected. It's worth mentioning that I am calling this line ...

Having trouble with the Express.js app.post request functionality

I'm facing a challenge with the Express.js library. I've been attempting to set up a basic post request with the route. I have body-parser installed and am using it for the post data. If I specifically include app.post, it doesn't work, ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...