简体   繁体   English

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

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

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')

标题值

I need to get value of title from span.我需要从 span 中获取 title 的值。 How can i do that?我怎样才能做到这一点?

In case /html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span is a corrct XPath locator如果/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)

Should work应该管用

To print the desired text you can use either of the following Locator Strategies :要打印所需的文本,您可以使用以下任一定位器策略

  • Using css_selector and get_attribute("innerHTML") :使用css_selectorget_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:使用xpath文本属性:

     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 :理想情况下,您需要为visibility_of_element_located()引入WebDriverWait ,并且您可以使用以下任一Locator Strategies

  • Using CSS_SELECTOR and text attribute:使用CSS_SELECTORtext属性:

     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") :使用XPATHget_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您可以在如何使用 Selenium - Python 检索 WebElement 的文本中找到相关讨论

print(followers_button.get_attribute('title'))

I am assuming you want to get the title attribute value using get_attribute and not the text.我假设您想使用 get_attribute 而不是文本来获取标题属性值。

Outputs:输出:

114 555

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM