How to locate and insert a value in a text box (input) using Python Selenium?
Asked Answered
K

3

117

I have the following HTML structure and I am trying to use Selenium to enter a value of NUM:

<div class="MY_HEADING_A">
    <div class="TitleA">My title</div>
    <div class="Foobar"></div>
        <div class="PageFrame" area="W">                
             <span class="PageText">PAGE <input id="a1" type="txt" NUM="" />  of <span id="MAX"></span> </span>
</div>

Here is the code I have written:

head = driver.find_element_by_class_name("MY_HEADING_A")
frame_elem = head.find_element_by_class_name("PageText")

# Following is a pseudo code. 
# Basically I need to enter a value of 1, 2, 3 etc in the textbox field (NUM) 
# and then hit RETURN key.
## txt  = frame_elem.find_element_by_name("NUM")
## txt.send_keys(Key.4)

How to get this element and enter a value‎‎‎‎‎‎‎? ‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎

Kenji answered 1/9, 2013 at 9:59 Comment(0)
A
223

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 
Antiphony answered 1/9, 2013 at 11:33 Comment(3)
ElementNotInteractableException: Message: ElementKeynote
is not reachable by keyboardKeynote
You should wait for the element to be present prior to interaction. input_element = WebDriverWait(driver, WAIT_TIME).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#a1"))) input_element.send_keys("1")Dashtikavir
R
1
web=driver.get('your web address')
input_1=driver.find_element(by=By.ID, value= 'id of element')
input_2=driver.find_element(by=By.ID, value= 'id of element')
input_3=driver.find_element(by=By.ID, value= 'id of element')

time.sleep(7)
input_1.send_keys(your value)
input_2.send_keys(your value)
input_3.send_keys(your value)
Ridgley answered 17/3, 2022 at 9:59 Comment(1)
I've reformatted your code, but please consider adding a description explaining why this is better than the accepted answer from 9 years ago. Is by=By.ID the new recommended usage? Has something changed in the API? Your answer will be a lot more valuable with some explanation.Coster
A
1

Currently in 2023 you have to import By.

Make the following imports:

from selenium.webdriver.common.by import By

Replace Input_you_want_to_send and THE_CLASS_OF_THE_ELEMENT below with the names you are using.

Input_you_want_to_send = driver.find_element(By.CLASS_NAME, 'THE_CLASS_OF_THE_ELEMENT')

You may also use by= and value= as Rizwan Syal stated but this is optional now.

Sending the keys remain the same as of 2023.

Arun answered 14/4, 2023 at 20:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.