0

I have two following XPath snippets and I want to merge them together to make one, can I do that?

xpath1 = /div/a[contains(@href,'location')]

xpath2 = /div/a[contains(@href,'city')]
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
dashkandhar
  • 83
  • 1
  • 7
  • 2
    maybe clarify a little.. are you trying to find more than one element? There is an "or" operator in xpath... (and "and") – pcalkins Jul 31 '20 at 20:27

2 Answers2

1

The two based Locator Strategies:

  • xpath1 = /div/a[contains(@href,'location')]
  • xpath2 = /div/a[contains(@href,'city')]

can be merged using notation as follows:

  • Using and:

    driver.findElement(By.xpath("//div/a[contains(@href,'location') and contains(@href,'city')]"))
    
  • Using or:

    driver.findElement(By.xpath("//div/a[contains(@href,'location') or contains(@href,'city')]"))
    
kjhughes
  • 106,133
  • 27
  • 181
  • 240
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

Shortest syntax is to use the union | operator. So in your case, you can use :

/div/a[contains(@href,'location')]|/div/a[contains(@href,'city')]

As a result you'll get elements which fulfill the first XPath expression + elements which fulfill the second XPath expression (+ elements which fulfill both expressions(not possible with your example since an anchor element supports only 1 @href attribute)).

E.Wiest
  • 5,425
  • 2
  • 7
  • 12