簡體   English   中英

如何使用 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)

應該管用

要打印所需的文本,您可以使用以下任一定位器策略

  • 使用css_selectorget_attribute("innerHTML")

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

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

理想情況下,您需要為visibility_of_element_located()引入WebDriverWait ,並且您可以使用以下任一Locator Strategies

  • 使用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)
  • 使用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"))
  • 注意:您必須添加以下導入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

您可以在如何使用 Selenium - Python 檢索 WebElement 的文本中找到相關討論

print(followers_button.get_attribute('title'))

我假設您想使用 get_attribute 而不是文本來獲取標題屬性值。

輸出:

114 555

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM