我怎样才能得到硒中的文本?

How can i get the text in selenium?

我想获取 selenium 中元素的文本。首先我这样做了:

  team1_names = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".home span"))
)
for kir in team1_names :
    print(kir.text)

没有成功。所以我尝试了这个:

team1_name=driver.find_elements_by_css_selector('.home span')
    print(team1_name.getText())

所以 team1_name.text 也不起作用。 那它有什么问题吗?

您需要注意以下几点:

  • 是检查元素是否存在于页面的 DOM 上的期望。这并不一定意味着该元素是可见的。
  • 此外, returns a 不是列表。因此,遍历 for 将不起作用。

解决方案

作为解决方案需要归纳 for the visibility_of_element_located() and you can use either of the following :

  • 使用 CSS_SELECTORtext 属性:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".home span"))).text)
    
  • 使用XPATHget_attribute():

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='home']//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


结尾

Link 到有用的文档:

  • get_attribute()方法Gets the given attribute or property of the element.
  • text属性returnsThe text of the element.
  • Difference between text and innerHTML using Selenium