Home > Software design >  How to get the value of title from span using Python and Selenium
How to get the value of title from span using Python and Selenium

Time:11-24

I have this code

followers_button = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span')

title value

I need to get value of title from span. How can i do that?

CodePudding user response:

In case /html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span is a corrct XPath locator

followers_button_text = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span').text
print(followers_button_text)

Should work

CodePudding user response:

To print the desired text you can use either of the following Locator Strategies:

  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "a[class*='na13'][href='/top_ukraine_girls/followers/']>span").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//a[@class='-na13' and @href='/top_ukraine_girls/followers/']/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, "a[class*='na13'][href='/top_ukraine_girls/followers/']>span"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='-na13' and @href='/top_ukraine_girls/followers/']/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

CodePudding user response:

print(followers_button.get_attribute('title'))

I am assuming you want to get the title attribute value using get_attribute and not the text.

Outputs:

114 555
  • Related