Home > Back-end >  How to insert some text within the input using Selenium and Python
How to insert some text within the input using Selenium and Python

Time:02-10

In a webpage I have the following element:

<div id="learning_form" >
                <table cellspacing="0" cellpadding="0">
                    <tbody><tr><td><input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;"></td></tr>
                </tbody></table>
                <div id="check"><h4 style="text-align: center;">Sprawdź</h4></div>
                <div id="special_characters"><div>&nbsp;</div><div>&nbsp;</div></div>
            </div>

How I can insert text here using selenium in python? I tried using:

driver.find_element(By.ID,"learning_form").send_keys("some text")

but it doesn't work.

Snapshot of the element:

enter image description here

CodePudding user response:

To send a character sequence to the 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, "div.learning_form#learning_form input#answer[placeholder='Odpowiedź']"))).send_keys("OłJeż")
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='learning_form' and @id='learning_form']//input[@id='answer' and @placeholder='Odpowiedź']"))).send_keys("OłJeż")
    
  • 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
    

CodePudding user response:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#answer"))).send_keys("value")

It seems you need to send values to the input with an id answer.

<input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;">

Import:

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