Home > Mobile >  How to print text (by its class name) in selenium, python?
How to print text (by its class name) in selenium, python?

Time:10-26

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>

CodePudding user response:

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