Home > front end >  Find previous element using Selenium Python
Find previous element using Selenium Python

Time:07-10

I have HTML:

<div >
    <div style="float: right;">100.00</div>
    <span >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?

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

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

CodePudding user response:

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)
    
  • Related