【问题标题】:Python Selenium get value from certain classPython Selenium 从某个类中获取价值
【发布时间】:2021-04-05 05:15:55
【问题描述】:

我正在尝试从此代码中获取value=" " 中的信息。 只要类中有 orange 这个词,我就想存储该值。

这种情况下的预期结果是将值“JKK-LKK”存储在变量中。

<input type="text" readonly="" class="form-control nl-forms-wp-orange" value="JKK-LKK" style="cursor: pointer; border-left-style: none;>

我尝试过使用

text = driver.find_elements_by_xpath("//*[contains(text(), 'nl-forms-wp-orange')]").get_attribute("value"))

但我明白了:

AttributeError: 'list' Object has no attribute 'get_attribute'.

我也尝试过getText("value"),但我得到的不是有效的 Xpath 表达式。

如果我只尝试使用

driver.find_elements_by_xpath("//*[contains(text(), 'nl-forms-wp-orange')]")

列表变为空。所以我觉得我可能会遗漏一些其他关键部分。 我可能做错了什么?

【问题讨论】:

  • 只需从 find_elements 中删除 s。您在整个列表而不是单个元素上使用 get_attribute。
  • driver.find_element_by_xpath("//input[contains(@class, 'nl-forms-wp-orange')]") 应该适合你。 text() 函数用于 innerHTML。

标签: python-3.x selenium xpath css-selectors webdriverwait


【解决方案1】:

要从包含 class 属性的元素中打印 value 属性的值,即 JKK-LKK 作为nl-forms-wp-orange,您可以使用以下Locator Strategies:

  • 使用css_selector:

    print(driver.find_element_by_css_selector("input.nl-forms-wp-orange").get_attribute("value"))
    
  • 使用xpath:

    print(driver.find_element_by_xpath("//input[contains(@class, 'nl-forms-wp-orange')]").get_attribute("value"))
    

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

  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input.nl-forms-wp-orange"))).get_attribute("value"))
    
  • 使用XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[contains(@class, 'nl-forms-wp-orange')]"))).get_attribute("value"))
    
  • 注意:您必须添加以下导入:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 2018-09-29
    • 2022-08-18
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多