【问题标题】:How to get the value of an element in Python + Selenium如何在 Python + Selenium 中获取元素的值?
【发布时间】:2018-06-16 19:19:15
【问题描述】:

我的 Python (3.6.3) 代码中有这个 HTML 元素(当然是 Selenium webelement):

<span class="ocenaCzastkowa masterTooltip" style="color:#000000;" alt="Kod: 
pd1<br/>Opis: praca domowa<br/>Waga: 2,00<br/>Data: 12.09.2017<br/>Nauczyciel: 
(NAME CENSORED)">5</span>

我想得到最后的值(在这种情况下是 5),我不知道如何得到它。 显然我不能使用webelement.get_attribute() 因为我不知道属性的名称。

【问题讨论】:

标签: python html selenium dom selenium-webdriver


【解决方案1】:

试试下面的代码:

span_element = driver.find_element_by_css_selector(".ocenaCzastkowa.masterTooltip")
span_element.text # This will return "5".

PS:你也可以使用span_element.get_attribute("value")

希望对你有帮助!

【讨论】:

  • 我很困惑。之前,我使用 find_elements_by_xpath(许多元素,这有效,所有的 webelements 都在那里) elementlist[x].getattribute('value') 不起作用。虽然现在,当我使用 find_element_by_css_selector(css_selector).get_attribute('value') 它返回所需的结果。谢谢。
  • 错误:selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document. 我尝试对这个错误进行一些研究,但没有走远。
  • @Koteu,如果我的回答有帮助 - 请在我的回答附近打勾。谢谢。
  • @Ratmir 是的,我知道,我会等一会儿,也许有人会找出问题所在。如果没有建议,我将接受您的回答。顺便说一句,谢谢你的即时回答。
  • @Koteu, .text 也必须工作。也许,需要等待(隐式或显式)。你没有推送你的代码。
【解决方案2】:

要打印 textContent 即 5,您可以使用以下任一 Locator Strategies:

  • 使用css_selector

    print(driver.find_element(By.CSS_SELECTOR, "div.ocenaCzastkowa.masterTooltip").text)
    
  • 使用xpath

    print(driver.find_element(By.XPATH, "//span[@class='ocenaCzastkowa masterTooltip']").text)
    

理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ocenaCzastkowa.masterTooltip"))).text)
    
  • 使用XPATH

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='ocenaCzastkowa masterTooltip']"))).text)
    
  • 注意:您必须添加以下导入:

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

您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2017-10-03
    • 2022-07-22
    相关资源
    最近更新 更多