Choose a random node from Xpath with multiple nodes using JavaScript WebdriverIO

Is there a way to retrieve a random node from an Xpath that contains multiple nodes whose count varies weekly? I am looking for a solution that would work in one of two ways:

  1. Return the total number of nodes corresponding to the Xpath, allowing me to then randomize the selection.
  2. Alternatively, provide a method to randomly select 1 out of 25 Xpaths.

I have attempted various approaches to solve this issue without success. One potential solution I found involves:

productCounter(){
        let c = document.evaluate('count(//*[@itemtype]/*[@data-order-bacu])', document, null, XPathResult.ANY_TYPE, null);
        console.log(c.numberValue);
}

This script should give me the count of nodes within the Xpath for randomizing purposes. However, when using webdriverIO, it throws an error:

document is not defined

As an alternative, I decided to try using the "browser.elements" function from webdriverIO. But I am uncertain if this approach will be helpful.

productCounter(){
        let a = browser.selectByIndex("//*[@itemtype]/*[@data-order-bacu]");
        console.log (a);
    }

The console.log output looks similar to the following. Could this information be used to determine the number of nodes as well?

{ sessionId: 'a45061ba0d9dfcf0b241877bb2951cc8',
  value:
   [ { ELEMENT: '0.5928327282420562-1',
       'element-6066-11e4-a52e-4f735466cecf': '0.5928327282420562-1',
       selector: '//*[@itemtype]/*[@data-order-bacu]',
       value: [Object],
       index: 0 },
     { ELEMENT: '0.5928327282420562-2',
       'element-6066-11e4-a52e-4f735466cecf': '0.5928327282420562-2',
       selector: '//*[@itemtype]/*[@data-order-bacu]',
       value: [Object],
       index: 1 },
     ...
     { ELEMENT: '0.5928327282420562-8',
       'element-6066-11e4-a52e-4f735466cecf': '0.5928327282420562-8',
       selector: '//*[@itemtype]/*[@data-order-bacu]',
       value: [Object],
       index: 7 },
     { ELEMENT: '0.5928327282420562-9',
       'element-6066-11e4-a52e-4f735466cecf': '0.5928327282420562-9',
       selector: '//*[@itemtype]/*[@data-order-bacu]',
       value: [Object],
       index: 8 } ],
  selector: '//*[@itemtype]/*[@data-order-bacu]',

Answer №1

Alright, I have discovered the solution to this particular issue:

generateDessert(Variation){
        const elements = browser.getElements("//*[@itemtype]/*[@data-order-tacus]");
        const randomNumber = Math.floor(Math.random()*elements.value.length);
        browser.elementIdElement(elements.value[randomNumber].ELEMENT.toString(), '.add-to-cart__submit').click();
        }

'add-to-cart__submit' was an additional component I had to include in the path due to each node/element having 4 distinct buttons.

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

The combination of React.js and debouncing on the onChange event seems to be malfunctioning

I recently incorporated a React component that triggers an event on change. Here's how I did it: NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler, 500); }, _searchBoxH ...

What is the best method for initializing Bootstrap data attributes API?

I've been puzzled by this issue for a while now. When trying to use the JavaScript components, I can't seem to grasp how to utilize them using the Data Attributes API, also known as the first-class API. For example, take the modal component ment ...

Error encountered while executing Selenium Web Driver's executeScript method: [JavascriptError: missing ) after argument list] with name: 'JavascriptError'

return driver.executeScript("\ console.log('Error: Incorrect selection');\ $('option:selected', 'select[name='who']').removeAttr('selected');\ $('select[name='who'] ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

How can I ensure eventual access to an object created in a React componentDidMount function without utilizing a deferred in ES6 Promises?

Thank you in advance for any help. I am delving into the world of ES6 native promises for the first time after previously using Q or Angular's $q service. I encountered a situation where using a deferred would have been convenient, but I was surprise ...

Can PHP encode the "undefined" value using json_encode?

How can I encode a variable to have the value of undefined, like in the JavaScript keyword undefined? When I searched online, all I found were results about errors in PHP scripts due to the function json_encode being undefined. Is there a way to represent ...

Converting Fractions to Decimals in a Table using Python-Selenium: Is it Possible?

Below is a snippet of the page source code: <thead> <tr> <td rowspan="3">Order</td> <td rowspan="3">Runner No.</td> <td rowspan="3">Name</td> <td colspan="6">Runn ...

Using JavaScript, create a regular expression with variables that can be used to identify and match a specific section of

Struggling to apply a regex (with 1 variable) to compare against a HTML code page stored as text. The HTML code is separated into an array, with each element representing a snippet like the one below. Each element showcases details of fictional Houses (na ...

Selenium's mouse click on specific coordinates is missing the mark

My task involves web scraping a page that relies on ActiveX controls for navigation, not for UI testing but for downloading data from a legacy application. The challenge lies in the fact that the top navigation is entirely ActiveX with javascript, making ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

What are the steps to execute my Python script on a Siteground hosting server?

I'm in the process of creating a website that includes a Python (.py) file, HTML, CSS, and JS files. I need guidance on how to execute my Python script on SiteGround from my hosting account in order to extract data from a specific site and generate a ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

iterating through the links of the products in order to extract information

My goal is to iterate through all the product links on multiple pages and have my driver open each link for data scraping. However, I'm experiencing an issue where only one product link is being opened and it's not moving on to the next one. Can ...

Enabling and disabling links in a Bootstrap dropdown menu with dynamic functionality on click

One interesting feature of bootstrap is that it allows users to disable links within its dropdown menu component by simply adding a class="disabled" into the corresponding <li> tag. I am looking to create some Javascript code so that when a user sel ...

What methods does Enzyme have for determining the visibility of components?

I am facing an issue with a Checkbox component in my project. I have implemented a simple functionality to hide the checkbox by setting its opacity : 0 based on certain conditions within the containing component (MyCheckbox) MyCheckBox.js import React fr ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

BrowserMobProxy fails to log any data in the HAR file

Trying to capture HTTP headers on a test page located at localhost:8000, but the HAR file does not seem to contain any information in the entry section. This is my code: BrowserMobProxyServer proxy = new BrowserMobProxyServer(); ...

The functionality of the button for selecting and deselecting all checkboxes is currently malfunctioning

I have a button in my ng-grid that successfully selects all checkboxes. However, I am also trying to implement functionality to deselect the checkboxes using the same button. Here is the initial code: app.directive('selectAll',function(){ ret ...

What's the most effective method for looping through a substantial array in order to save data into SQLite using Node.js?

Let's consider a scenario where I am inserting data into a table using a for loop like the example below: ... for(let i=0;i<data.length; i++){ db.run(`INSERT INTO db (a, t, p, q, bM) VALUES (?, ?, ?, ?, ?)`, [data[i].a, data[i].t, data[i].p, da ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...