Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find previous element using Selenium Python

I have HTML:

<div class="value">
    <div style="float: right;">100.00</div>
    <span class="yellow">Frequency:</span>
</div>

With selenium By.XPATH ‘//*[text()="Frequency:"]’ I’m able to locate the <span> element. My goal is to get the innerText of the previous <div>.

Can I do it with selenium or should I use bs4 for this task?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried selenium.parent with documentation, but unable to do.

PS: I can’t find the parent element or the div I need directly.

>Solution :

To print the text from the <div> tag i.e. 100.00 wrt the <span> you can use either of the following locator strategies:

  • Using xpath and get_attribute("innerHTML"):

    print(driver.find_element(By.XPATH, "//span[text()='Frequency:']//preceding::div[1]").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//span[text()='Frequency:']//preceding::div[1]").text)
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading