如何使用 Python 和 Selenium 从 span 中获取 title 的值

How to get the value of title from span using Python and Selenium

我有这个代码

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

我需要从 span 中获取 title 的值。我该怎么做?

如果 /html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span 是正确的 XPath 定位器

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)

应该可以

要打印 title 属性的 value,您可以使用以下任一方法 :

  • 使用css_selector:

    print(driver.find_element(By.CSS_SELECTOR, "a[class*='na13'][href='/top_ukraine_girls/followers/']>span").get_attribute("title"))
    
  • 使用xpath:

    print(driver.find_element(By.XPATH, "//a[@class='-na13' and @href='/top_ukraine_girls/followers/']/span").get_attribute("title"))
    

理想情况下你需要诱导 for the visibility_of_element_located() and you can use either of the following :

  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[class*='na13'][href='/top_ukraine_girls/followers/']>span"))).text)
    
  • 使用XPATH:

    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"))
    
  • 注意:您必须添加以下导入:

    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

print(followers_button.get_attribute('title'))

我假设您想使用 get_attribute 而不是文本来获取标题属性值。

输出:

114 555