Paulina
Paulina

Reputation: 81

Selenium Python: How to extract text within a href element

I am looking for a way to extract/print text which is located within a href element.

Snapshot of the HTML: snapshot of HTML

Code trials:

WebDriverWait(driver, 20).until(EC.visibility_of_element_located(By.XPATH('//div[contains(@class, "style1")]')))
driver.find_element_by_xpath('//div[contains(@class, "style1")]').text

Error massage: TypeError: 'str' object is not callable

Many more trials to locate this "0" without success. The number will change when some open 'tickets' appear in the system.

How this could be done?

Upvotes: 1

Views: 70

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193308

You were close enough. The untill() method accepts a tuple. Hence you see the error:

TypeError: 'str' object is not callable

Moreover the text 0 is within the descendant <a> of the <div>.


Solution

Your effective line of code will be:

  • Using text attribute:

    print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'style1')]/a"))).text)
    
  • Using get_attribute():

    print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'style1')]/a"))).get_attribute('textContent'))
    

Alternative

As an alternative considering thw href attribute of the <a> tag you can use:

print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='style1']/a[starts-with(@href, '/scp/endeavour/deviationDetailsPortlet')]"))).text)

Upvotes: 0

KunduK
KunduK

Reputation: 33384

if you print this, it should return the value 0

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH,'//div[contains(@class, "style1")]/a'))).text)

You need to change this from

driver.find_element_by_xpath('//div[contains(@class, "style1")]').text

to

print(driver.find_element(By.XPATH,'//div[contains(@class, "style1")]/a').text)

You need to import this library.

from selenium.webdriver.common.by import By

Upvotes: 1

Related Questions