Home > Software engineering >  Python Selenium how to target an h3 tag within a specific div?
Python Selenium how to target an h3 tag within a specific div?

Time:10-15

I have several h3 tags within a page, none of them have a class or id to target but a specific one that I need is within another larger div. The code is below:

<div class="profile-info">
     <div class="photo-wrapper">
     </div>
     <h3>
     Text I need
     </h3>

</div>

How do I target and save the text within that h3 tag?

CodePudding user response:

If class photo-wrapper is unique.

You can use below xpath :

//div[@class='photo-wrapper']//following-sibling::h3

if there are more than one h3 tag, please use xpath indexing:

(//div[@class='photo-wrapper']//following-sibling::h3)[1]

to represent first child h3.. [2] for second h3 and so on..

or using child :

//div[@class='profile-info']//child::h3

to locate the first child under div which has profile-info class.

(//div[@class='profile-info']//child::h3)[1]

to represent first element as well with xpath indexing.

(//div[@class='profile-info']//child::h3)[2]

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  • Related