python清空文本框,清除硒并在textarea文本框中输入文本[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!

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值