skip to Main Content

I am trying to get the text that is located outside of this label and inside the div

<div style="color:red;">
<label> Total Amount Due:</label>
$0.00
</div>

Here all I am trying to extract is the $0.00

I have tried using the xpath of the div to get the number but it still includes the text of the label saying Total Amount Due: $0.00

amount_finder  =driver.find_elements_by_xpath("//body[1]/div[4]/div[1]/div[2]/div[2]/div[3]/div[1]/div[1]/div[1]/font[1]/div[1]/table[2]/tbody[1]/tr[1]/td[1]/div[10]")
for amount in amount_finder:
    print(amount.text)

I can’t seem to figure out a way to just get the $0.00. I am new to to this and having trouble search previous posts on here and applying it to my situation. I see various recommendations of using following-sibling but can’t get that to work.

2

Answers


  1. It is because you are looping through all the elements in amount_finder

    You just need to get the text from the div element itself.

    amount = driver.find_element(By.XPATH, '//body[1]/div[4]/div[1]/div[2]/div[2]/div[3]/div[1]/div[1]/div[1]/font[1]/div[1]/table[2]/tbody[1]/tr[1]/td[1]/div[10]').text()
    print(amount)
    

    You can also use simply use Xpath or Query Selector instead of Full Xpath.

    Use from selenium.webdriver.common.by import By, if you are running this code. Using By is much easier compared to old find_elements_by_xpath

    Login or Signup to reply.
  2. You can use text() node of XPath:

    //div/text()[2]
    

    but, since it is not an element but a text node, selenium cannot process it. So the solution is to run XPath by Javascript:

    node_text = driver.execute_script("return document.evaluate('//div//text()[2]', document).iterateNext().textContent;")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search