Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the elements only after a specific text in html using selenium python

Lets say I have following HTML Code

<div class="12"> 
  <div class="something"></div> 
</div>
<div class="12"> 
  <div class="34"> 
    <span>TODAY</span> 
  </div>
</div> 
<div class="12"> 
  <div class="something"></div> 
</div> 
<div class="12"> 
  <div class="something"></div> 
</div>

Now If I use driver.find_elements_by_class_name("something") then I get all the classes present in the HTML code. But I want to get classes only after a specific word ("Today") in HTML. How to exclude classes that appear before the specific word. Next divs and classes could be at any level.

like image 463
Pawan Aichra Avatar asked Jun 02 '18 15:06

Pawan Aichra


1 Answers

You can use search by XPath as below:

driver.find_elements_by_xpath('//*/text()[.="some specific word"]/following-sibling::div[@class="something"]')

Note that you might need some modifications in case your real HTML differs from provided simplified HTML

Update

replace following-sibling with following if required div nodes are not siblings:

driver.find_elements_by_xpath('//*/text()[.="some specific word"]/following::div[@class="something"]')
like image 200
Andersson Avatar answered Sep 30 '22 20:09

Andersson