dashkandhar
dashkandhar

Reputation: 93

How to create a custom Xpath which uses contains method for two different strings

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')]

Upvotes: 0

Views: 769

Answers (2)

E.Wiest
E.Wiest

Reputation: 5905

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

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193088

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')]"))
    

Upvotes: 1

Related Questions