0

I want to extract text using selenium in Python from an html. My text is under the id tag and when I try to retrieve the text this way gives me error.

enter image description here

date=browser.find_element_by_id('ctl00_ContentPlaceHolder1_lblIncDate')
date2=date.text
date1.append(date)

AttributeError                            Traceback (most recent call last)
<ipython-input-21-20d6df14a340> in <module>()
     37 date1.append(date)
     38 userid_element = browser.find_elements_by_id('ctl00_ContentPlaceHolder1_lblIncDate')
---> 39 userid = userid_element.text
     40 userid1.append(userid)
     41 time.sleep(20)

AttributeError: 'list' object has no attribute 'text'

Also, I tried with xpath but does not really work:

date2=date.text
date1.append(date)

  File "<ipython-input-19-8b8e7fb86782>", line 35
    date=browser.find_element_by_xpath(''//span[@id= 'ctl00_ContentPlaceHolder1_lblIncDate' ]'')
                                                ^
SyntaxError: invalid syntax
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Alicia Pliego
  • 181
  • 10

2 Answers2

1

You haven't presented the failing code, but from the traceback it's visible that you're using plural version (browser.find_elements_by_id) instead of singular browser.find_element_by_id.

ipaleka
  • 3,745
  • 2
  • 13
  • 33
  • Plus their other error where they needed " not ' i.e. date=browser.find_element_by_xpath("//span[@id= 'ctl00_ContentPlaceHolder1_lblIncDate']") – QHarr Aug 21 '19 at 20:20
1

To retrieve the text 4/20/2016 you need to induce WebDriverWait for the visibility_of_element_located and you can use either of the followingcan use Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span#ctl00_ContentPlaceHolder1_lblIncDate"))).get_attribute("innerHTML"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//span[@id='ctl00_ContentPlaceHolder1_lblIncDate']"))).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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352