Matthew
Matthew

Reputation: 379

Selenium clearing and typing in text into textarea text box [Python]

I am using Selenium to do some scraping. I used the following code to input the text into a textarea text box:

def clear_and_send_key_then_wait(element, key, sleep_time = 1):
# For some reason this does not work
#     element.clear() 

# This works
    element.send_keys(Keys.CONTROL + "a");
    element.send_keys(Keys.DELETE);

# Input text
    element.send_keys(key)
    time.sleep(sleep_time)

target_textbox = driver.find_element_by_xpath(
"""/html/body/div[2]/div/div[2]/div[1]/div[4]/div[1]/div/textarea""")
clear_and_send_key_then_wait(target_textbox, 'z'*100000)

Q1: Why doesn't element.clear() remove the existing text in the textbox?

Since a lot of texts have to be typed into the text box, the above method is too slow. Instead, I use the first Javascript method execute_script suggested here.

However, simply doing the following does not fill the text box.

driver.execute_script("arguments[0].value=arguments[1];", 
                      target_textbox, "z"*100000)

The text only appears after another send_key command follows immediately after the execute_script line:

driver.execute_script("arguments[0].value=arguments[1];", 
                      target_textbox, "z"*100000)
target_textbox.send_keys(Keys.ENTER)

Q2: Why is the subsequent target_textbox.send_keys(Keys.ENTER) required? It seems like in the link, the author does not need to send Enter key. Is it a different type of text box? If so, what are the different types of text boxes and do they all have different behaviors?

Thanks in advance!

Upvotes: 0

Views: 884

Answers (1)

Sers
Sers

Reputation: 12255

Selenium doesn't fire any keyboard or mouse events on clear. Same happens when you set value using JavaScript. Probably the website waits for the keys event to proceed some work for the textarea's value and trigger for that is send_keys with any key.

You can try the code below, \ue007 is Enter key:

driver.execute_script("arguments[0].value=arguments[1];", target_textbox, "z"*100000 + "\ue007")

Upvotes: 2

Related Questions