Mohammed
Mohammed

Reputation: 334

Find Element By Text Using Selenium WebDriver

I have the following HTML page and I am using Selenium under python to extract some data from the page HTML

<div class="secondary-content-col col-xs-12">
<div class="row">
<div class="col-xs-12">
<h2 class="h4"><span>Uthyres av:</span> Test</h2>
</div>
</div>
</div>

I want to get the Test text from tag, I have tried

driver.find_elements_by_xpath("//*[contains(., 'Uthyres')]")

but it says element no found! any idea how can I solve it

Upvotes: 0

Views: 8349

Answers (1)

akuiper
akuiper

Reputation: 214927

You could try this xpath:

//*[contains(text(), 'Uthyres')]/parent::*/text()

instead of contains(., ...) use contains(text(), ...) and then go to the parent node and extract the text. Note Test here is the text node of tag h2 instead of span.


Demonstration using lxml:

from lxml import etree

e = etree.fromstring("""<div class="secondary-content-col col-xs-12">
<div class="row">
<div class="col-xs-12">
<h2 class="h4"><span>Uthyres av:</span> Test</h2>
</div>
</div>
</div>""")

e.xpath('//*[contains(text(), "Uthyres")]/parent::*/text()')
# [' Test']

Upvotes: 1

Related Questions