Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and Selenium xpath for selecting with multiple conditions

I have the following code in selenium but continue to get a syntax error. I'm trying to select an element based on multiple conditions.

choices = driver.find_elements_by_xpath("//div[contains(.,'5') and [contains(@class, 'option')]]")$

Thanks for any help you can give.

like image 321
Noah Ratliff Avatar asked Mar 23 '18 23:03

Noah Ratliff


People also ask

Can we use and condition in XPath?

Using OR & AND In the below XPath expression, it identifies the elements whose single or both conditions are true. Highlight both elements as 'First Name' element having attribute 'id' and 'Last Name' element having attribute 'name'. In AND expression, two conditions are used.

How do I combine two conditions in XPath?

In XPath expression single attribute will identify the multiple conditions then we can use more than one attribute in the expression of the path for locating a single element. For writing multiple conditions we can apply the AND and OR conditions.

How do you handle multiple elements with the same XPath in Selenium?

provide numbers to your xpath! For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.


1 Answers

As per the xpath you have shared as follows :

choices = driver.find_elements_by_xpath("//div[contains(.,'5') and [contains(@class, 'option')]]")$

You need to consider a few facts :

  • The multiple conditions for selecting the <div> tag can't be within nested []. Either you have to specify within one [] or within multiple []s.
  • The xpath shouldn't end with unwanted characters e.g $

Solution

You can rewrite the xpath in either of the following ways :

choices = driver.find_elements_by_xpath("//div[contains(.,'5') and contains(@class, 'option')]")
# or
choices = driver.find_elements_by_xpath("//div[contains(.,'5')][contains(@class, 'option')]")
like image 54
undetected Selenium Avatar answered Sep 23 '22 21:09

undetected Selenium