Bernard Parah Bernard Parah - 1 month ago 8
HTML Question

Selenium : Find nested div with specific plain text using xpath

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?

Answer

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]
Comments