Home > Software engineering >  How to target a specific div class within a specific parent div class, python selenium
How to target a specific div class within a specific parent div class, python selenium

Time:10-15

I have two divs that look like this:

<div id="RightColumn">
   <div class="profile-info">   
       <div class= "info">
       </div>
       <div class="title">
       </div>
   </div>
</div>

How do I target the internal div labelled "title"? It appears multiple times on the page but the one that I need to target is within "RightColumn".

Here is the code I tried:

mainDIV = driver.find_element_by_id("RightColumn")
targetDIV = mainDIV.find_element_by_xpath('//*[@class="title"]').text

Unfortunately the above code still pulls all title divs on the page vs the one I need within the mainDiv.

CodePudding user response:

//div[@id='RightColumn']//child::div[@class='title']

this should get the job done.

first use id RightColumn to taget div and then title class div is a child.

CodePudding user response:

This will select the first title div under this element:

mainDIV.find_element_by_xpath('.//div[@class="title"]

However, this will select the first title on the page:

mainDIV.find_element_by_xpath('//div[@class="title"]

Try:

targetDIV = mainDIV.find_element_by_xpath('.//div[@class="title"]').text

Note as of Selenium 4.0.0, the find_element_by_* functions are deprecated and should be replaced with find_element().

targetDIV = mainDIV.find_element(By.XPATH, './/div[@class="title"]').text

Reference:

WebDriver API - find_element_by_xpath

  • Related