Home > Mobile >  Is there a way to concatenate a variable in xpath which is within a single quote?
Is there a way to concatenate a variable in xpath which is within a single quote?

Time:09-09

I'm using nodeJS, this is what I'm trying:

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...
    );
  }
}

trying to insert 'i' of for loop variable in xpath. Couldn't add a double quote, xpath becomes unidentifiable for eg this:

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

Does not get identified.

This is how the xpath is discoverable in browser:

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

CodePudding user response:

You can use a String.format to format the XPath expression with the i index value, something like this:

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

CodePudding user response:

Building and compiling a new XPath expression for each value of i is going to be very inefficient, although it's quite possible. I'm not familiar with the XPath API you are using, but many XPath APIs allow you to compile an XPath expression containing a variable reference, for example

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

and then to execute it repeatedly with different values of the parameter.

Alternatively, you can easily retrieve all the items in one go

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

and then iterate over them in the host language (Javascript in this case).

  • Related