简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM