2

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

这种情况下的预期结果是将值“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')]")

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

4

1 回答 1

2

要从包含属性的元素中打印属性的值,即JKK-LKK ,您可以使用以下任一定位器策略nl-forms-wp-orange

  • 使用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"))
    

理想情况下,您需要诱导WebDriverWait并且visibility_of_element_located()您可以使用以下任一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
    
于 2020-12-28T12:24:03.090 回答