I have the following HTML structure and I am trying to use Selenium to enter a value
<div >
<form id="main-form" action="/pushData" method="post">
<input type="hidden" name="_token" value="bnePp0JmVaVYuaTIAfuVIGT2y7usVssX3vQrAGaz">
<input type="text" id="input-url" name="url" placeholder="Paste URL to shorten">
<button id="button-submit">Cut</button>
</form>
</div>
Here is my code
driver.find_element_by_id("input-url").send_keys("test")
driver.find_element_by_id("button-submit").click()
I want to get this element and enter a value.
CodePudding user response:
Select element by id:
inputElement = driver.find_element_by_id("input-url")
inputElement.send_keys('testing')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
CodePudding user response:
Selenium 4.3.0: Deprecated find_element_by_* and find_elements_by_* are now removed (#10712)
The following code will work:
[..]
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
[..]
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'input-url'))).send_keys('test')
button_to_be_clicked = browser.find_element(By.ID, 'button-submit')
button_to_be_clicked.click()
CodePudding user response:
To send a character sequence to the <input>
element you can use either of the following locator strategies:
Using css_selector:
driver.find_element(By.CSS_SELECTOR, "input.url-input#input-url[name='url'][placeholder='Paste URL to shorten']").send_keys("Phonex")
Using xpath:
driver.find_element(By.XPATH, "//input[@class='url-input' and @id='input-url'][@name='url' and @placeholder='Paste URL to shorten']").send_keys("Phonex")
Ideally to send a character sequence to the <input>
element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.url-input#input-url[name='url'][placeholder='Paste URL to shorten']"))).send_keys("Phonex")
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='url-input' and @id='input-url'][@name='url' and @placeholder='Paste URL to shorten']"))).send_keys("Phonex")
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