Python and Selenium xpath for selecting with multiple conditions
Asked Answered
G

2

9

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.

Garniture answered 23/3, 2018 at 23:15 Comment(2)
What error are you getting ?Chronon
try //div[contains(.,'5') and contains(@class, 'option')]Expertism
C
12

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')]")
Cestus answered 24/3, 2018 at 21:18 Comment(0)
E
1

Here's an example without using "contains()":

driver.find_element(By.XPATH, '//input[@name="name" and @value="value"]')
Epicycle answered 2/9, 2022 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.