清除硒并在textarea文本框中输入文本[Python] [英] Selenium clearing and typing in text into textarea text box [Python]

查看:327
本文介绍了清除硒并在textarea文本框中输入文本[Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Selenium进行刮擦.我使用以下代码将文本输入到textarea文本框中:

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)

问题1:为什么element.clear()不删除文本框中的现有文本?

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

由于必须在文本框中键入很多文本,因此上述方法太慢.相反,我使用了第一个Javascript方法execute_script建议在此处.

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)

仅在execute_script行之后紧接着另一个send_key命令之后,文本才会出现:

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)

问题2:为什么需要随后的target_textbox.send_keys(Keys.ENTER)?似乎在链接中,作者不需要发送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?

提前谢谢!

推荐答案

Selenium不会清除任何键盘或鼠标事件.使用JavaScript设置值时也会发生同样的情况.网站可能正在等待按键事件以继续进行textarea的值的某些工作,并使用任意按键触发该值send_keys.

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.

您可以尝试下面的代码,\ue007是Enter键:

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

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

这篇关于清除硒并在textarea文本框中输入文本[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆