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

拈花ヽ惹草 提交于 2020-01-24 00:35:14

问题


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!


回答1:


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")


来源:https://stackoverflow.com/questions/59740310/selenium-clearing-and-typing-in-text-into-textarea-text-box-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!