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?

Community
  • 1
  • 1

2 Answers2

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]
har07
  • 88,338
  • 12
  • 84
  • 137
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()
Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73