14

I am using Python / Selenium and am trying to select an input box that does not have an ID:

HTML

<div class="form-group">
    <input type="email"
           class="form-control"
           name="quantity"
           placeholder="Type a quantity">
</div>

Code

inputElement = driver.find_element_by_id("quantity")

What is the best way to select this element, by name?

2

4 Answers 4

15

find_element_by_name() method would fit here:

driver.find_element_by_name("quantity")
Sign up to request clarification or add additional context in comments.

6 Comments

The answer is almost in the title ;)
now this is deprecated, use ind_element(by=By.NAME, value=name) instead
Typos are unhelpful. It is at least find_element(by=By.NAME, value=name)
Something like "from selenium.webdriver.common.by import By" is required for "By.NAME" to work.
|
9

In September 2022 with Selenium 4.4.0 the correct answer would be:

from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
inputElement = driver.find_element(by=By.NAME, value='quantity')

3 Comments

Yes, the "from selenium.webdriver.common.by import By" line is crucial. Otherwise the result may be (Pylint) "E0602: Undefined variable 'By' (undefined-variable)"
Though it does not work for a variable number of elements (dynamic content), say 0, 1, or 2: An exception is thrown, stopping the test run, if the element does not exist: "selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element"
And it, presumably, only returns the first element if there is more than one.
0

I have used this method to collect attributes from elements many times:

for i in browser.find_elements_by_class_name("form-control"):
    print i.get_attribute("name")

Comments

0

Preferable is to use explicit wait:

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


driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
input_element = wait.until(EC.presence_of_element_located((By.NAME, 'quantity')))

More about waits here

2 Comments

Why is it preferable to use explicit wait?
Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load. If one sets an implicit wait command, then the browser will wait for the same time frame before loading every web element. This causes an unnecessary delay in executing the test script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.