Python Selenium get value from certain class

Viewed 502

I am trying to get the information in value=" " from this code. As long as the class has the word orange in it, I want to store the value.

Expected result in this case is storing value "JKK-LKK" in a variable.

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

I have tried using

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

But I get:

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

I've also tried getText("value") but I get is not a valid Xpath expression.

If I try only using

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

The list becomes empty. So I feel like I might be missing some few other key pieces. What might I be doing wrong?

1 Answers

To print the value of the value attribute i.e. JKK-LKK from the elements containing class attribute as nl-forms-wp-orange you can use either of the following Locator Strategies:

  • Using css_selector:

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

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

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

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

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[contains(@class, 'nl-forms-wp-orange')]"))).get_attribute("value"))
    
  • Note : You have to add the following imports :

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