Is it possible to merge a variable within single quotes in XPath?

Currently working with nodeJS and experimenting with the following code snippet:

for (let i = 1; i <= elSize; i++) {
  try {
    let DeviceName = await driver
      .findElement(By.xpath("//span[@class='a-size-medium a-color-base a-text-normal']['i']"))
      .getText();
    console.log(i + ". Device Name: " + DeviceName + "\n");
  } catch (e) {
    await driver.executeScript(
      ...
      catch statements...
    );
  }
}

Attempting to include the 'i' variable from the for loop in the xpath. Facing issues due to the absence of double quotes, resulting in an unrecognizable xpath like this one:

driver.findElement(By.xpath("(//span[@class='a-size-medium a-color-base a-text-normal')["+ i +"]")).getText();

This causes the xpath to be unrecognized.

Here is an example of how the xpath can be identified in the browser:

//span[@class='a-size-medium a-color-base a-text-normal']['i']

Answer №1

To customize the XPath expression using the index value i, you can utilize the String.format method as shown in the following snippet:

var selector = "(//span[@class='a-size-medium a-color-base a-text-normal'])[{0}]"
for (let i = 1; i <= totalElements; i++) {
  var updatedSelector = String.format(selector, i);
  try {
    let ElementText = await driver.findElement(By.xpath(updatedSelector)).getText();
    console.log(i + ". Element Text: " + ElementText + "\n");
  } catch (e) {
    await driver.executeScript(
      ...
      appropriate catch block...
    );
  }
}

Answer №2

To avoid inefficiency, consider building a single XPath expression that includes a variable reference for i. This can be executed multiple times with different values of the parameter. For example:

//span[@class='a-size-medium a-color-base a-text-normal'][$i]

Another approach is to fetch all items at once using an XPath expression like:

//span[@class='a-size-medium a-color-base a-text-normal']

You can then iterate over the retrieved items in your host language (such as Javascript).

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

How can I pass a PHP variable to a JavaScript variable using PHP and JQuery/JavaScript?

I am facing a challenge with a large <select> input that is used across multiple pages. My idea is to separate this dropdown box into its own PHP file and load it externally using JQuery. Is this approach feasible? Here's an outline of what I ha ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

Utilizing Selenium WebDriver in Python to locate and interact with WebElements

Currently, I am utilizing Selenium for real-time web scraping. However, I am encountering issues searching for a specific WebElement even though the documentation indicates that it is feasible. while True: try: member = self.pdriver.find_all(" ...

"Enhancing the Today Button in FullCalendar with Custom Functionality

My issue lies with the implementation of fullCalendar. Specifically, I am utilizing the week view (defaultView: 'basicWeek') with the toolbar buttons for 'today', 'prev', and 'next'. The problem arises when I click t ...

What is Angular's approach to managing the @ symbol in view paths?

I found some interesting data lake sources on AWS. I came across their package.js file, which includes the following code: '@package': { templateUrl: 'package/package.html', controller: 'PackageCtrl' } I am curious a ...

Conducting selenium tests within a docker-compose setup

I currently have 3 docker containers: Web application End-to-end tests: Specifically selenium tests for the aforementioned web app Selenium: Utilizing this image from To launch these containers using compose, I use the following configuration: web-app: ...

What is the process of transforming a basic JavaScript function into a TypeScript function?

As a Java developer diving into TypeScript for frontend development, I've encountered a simple JavaScript code snippet that I'd like to convert to TypeScript. The original JavaScript code is: let numbers = [123, 234, 345, 456, 567]; let names = ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

The art of transforming properties into boolean values (in-depth)

I need to convert all types to either boolean or object type CastDeep<T, K = boolean> = { [P in keyof T]: K extends K[] ? K[] : T[P] extends ReadonlyArray<K> ? ReadonlyArray<CastDeep<K>> : CastDeep<T[P]> ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

Creating a legitimate string using a function for jqGrid editoptions value: What's the best way to do it?

I am encountering an issue while trying to create a string for the editoptions value using a function. The desired string format is as follows: '1:Active;2:Inactive;3:Pending;4:Suspended'. Strangely, when I manually input this string as the value ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

What is the best way to verify async actions that update the UI in my React Native application?

Currently, my setup involves utilizing jest alongside @testing-library/react-native. Below is a snippet of code: Upon clicking a button, a function is dispatched: onPress(_, dispatch) { dispatch(getUserAddresses()); }, This dispatched functi ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...