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')]
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
dashkandhar
  • 15
  • 1
  • 4
  • 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
  • 89,675
  • 16
  • 141
  • 199
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
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,122
  • 2
  • 4
  • 11