1

I have two paths :

 driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]/span")).click();
 driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]")).click();

How can I handle both via contains so that the first or second version will be searched - with one constancy.

grandecalvo
  • 213
  • 1
  • 3
  • 10

4 Answers4

1
WebElement thingie = driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]"))

if (thingie.findElements(By.tagName("span")).size() != 0) {
    thingie.findElement(By.tagName("span")).click();
} else {
    thingie.click();
}

Create a starting point WebElement, then check to see if the <span> exists. If so, click on the span version, otherwise, click the td directly.

MivaScott
  • 1,763
  • 1
  • 12
  • 30
1

You can use the pipeline sign |. The pipeline sign acts as a union of the elements that are returned from each part of the expression

driver.findElement(By.xpath("//tr[contains(@id,'"+variable+"')]/td[5] | //tr[contains(@id,'"+variable+"')]/td[5]/span")).click();

The contains looks not necessary, the expression could be:

driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]/span | //tr[@id='"+variable+"']/td[5]")).click();

Reference: Two conditions using OR in XPATH

K. B.
  • 3,342
  • 3
  • 19
  • 32
0

To rewrite the xpaths including the contains keyword along with a variable expression you can use the following lines of code :

 driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]/span")).click();
 driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]")).click()
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You can use REGEX like this:

driver.findElement(By.xpath("[@value='<REGEX>']")).click();

So the REGEX for your xPath will be (as String):

"^[//tr\[@id='" + variable + "\]/td\[5\]][/span]?$"

So you need to paste this into and should work.

LenglBoy
  • 1,451
  • 1
  • 10
  • 24