0

I need to find a certain text in a nested div that has no class or id.

This is a structure of the html.

<div class="active_row">
  <div class="outcomes">
   <div class="event_outcome" onclick="doSomething">
     <div>Target Text</div>
   </div>
  </div>
</div>

I tried accessing the text directly using the example I got from here.

driver.find_elements_by_xpath("//div[contains(., 'Target Text')]")

This returns a list of elements that contain the target text but nothing happens when I run the click method on them.

What's the best way to set this query to find the text and then click on the div with event_outcome class?

2 Answers 2

2

To select the div with event_outcome class, you can add a predicate in your XPath to check class attribute value :

//div[contains(., 'Target Text') and @class='event_outcome']

or add a predicate to check existence of onclick attribute :

//div[contains(., 'Target Text') and @onclick]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks!!! I combined the two predicates, then printed the result to confirm using .text. Now it clicks!!! Thank you!
2

What's the best way to set this query to find the text and then click on the div with event_outcome class?

You should try using below xpath which would returns <div class="event_outcome" onclick="doSomething"> with text Target Text which would fullfil all your needs as below :-

element = driver.find_element_by_xpath(".//div[contains(., 'Target Text') and @class='event_outcome']")
print(element.text)
element.click()

Or you can also get the same with exact match of the inner text using normalize-space() function of the xpath as below :-

element = driver.find_element_by_xpath(".//div[normalize-space()='Target Text' and @class='event_outcome']")
print(element.text)
element.click()

1 Comment

Lol...thanks! Just did the same thing before seeing your answer. Adding normalize just saved me extra work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.