Home > Mobile >  How to get span value without class on python selenium
How to get span value without class on python selenium

Time:11-14

I'm new on python, just started learning, I try to get value span on other website and I'm trying to get value on this picture on red mark , but I still get an error.

Snapshot of the HTML:

Snapshot

CodePudding user response:

To print the text 4 hours 30 minutes you can use either of the following Locator Strategies:

  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "div.lab-preamble__details.subtitle-headline-1 > span").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//div[@class='lab-preamble__details subtitle-headline-1']/span").text)
    

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.lab-preamble__details.subtitle-headline-1 > span"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='lab-preamble__details subtitle-headline-1']/span"))).get_attribute("innerHTML"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


References

Link to useful documentation:

CodePudding user response:

If you're using only selenium to find element you can try to get this element using find_element_by_xpath.

To get xpath fast and easy you can right-click element in Chrome DevTools and in "Copy" section there is the "Copy xpath" option.

  • Related