0

I have this code:

try:
    price = wait(driver, 10).until(EC.presence_of_element_located((By.ID, "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"))).text
    print(price)
except Exception:
    print("element not found")
finally:
    driver.quit()

What I want it to do, is to copy the stock price on yahoo and print it in the terminal. I was thinking, that it might not work because the stock price is changing and so does the class or something, but after trying to copy an unmoving element, it still doesn't work. What am I doing wrong?

The code of element on the site looks like that:

<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="31">41.24</span>
3
  • Can you please provide the website you're scraping? Commented Oct 25, 2021 at 17:29
  • It's yahoo so I would believe you could share the link to the page ? Commented Oct 25, 2021 at 18:08
  • The exact site I was using was 'finance.yahoo.com/quote/NIO?p=NIO&.tsrc=fin-srch' Commented Oct 25, 2021 at 20:23

1 Answer 1

1

You are trying to locate that element by a wrong locator.
The desired element has a class attribute value of Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib), it is not an id attribute.
So instead of By.ID, you should rathe use By.CSS_SELECTOR.
Also you should use visibility_of_element_located instead of presence_of_element_located.
Please try this:

try:
    price = wait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.Trsdu(0.3s).Fw(b).Fz(36px).Mb(-4px).D(ib)"))).text
    print(price)
except Exception:
    print("element not found")
finally:
    driver.quit()

Or this:

try:
    price = wait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span[data-reactid="31"]"))).text
    print(price)
except Exception:
    print("element not found")
finally:
    driver.quit()
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, thank you! I was trying CSS_SELECTOR but had no idea I have to use visibility instead of presence. Why is that?
There is a process of creation, rendering the elements on the page while it is being loaded. So when the element is initially appearing on the page, existing, it is still not finally completed, will not be clickable and still not including the text it will finally include. So presence_of_element_located catches and returns the element while it is existing on the page but maybe not finally ready while visibility_of_element_located detects the element on more mature stage when it is visible and in most cases finally completed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.