python selenium使用clear无法清除默认值的问题

发布时间 2023-04-04 17:06:33作者: 小飞桃来咯

页面自带输入框默认值时,想要修改输入框的内容,使用clear()后再使用send_keys(),结果无法起到清除文本框内容的作用,反而会在输入框默认值后面追加内容。

解决方法:

一、通过键盘的快捷键进行全选,然后删除,彻底解决

from selenium.webdriver.common.keys import Keys
ele= self.driver.find_element_by_id("id")
ele.send_keys(Keys.CONTROL, "a")
ele.send_keys(Keys.DELETE)
ele.send_keys("tao")

二、通过双击,然后send_keys()

缺点:有时候双击不一定能选中所有内容,可能存在无法清除的风险

from selenium.webdriver.common.action_chains import ActionChains
element= self.driver.find_element_by_id("id")
# 通过双击全选输入框内容,然后send_keys(),起到清除输入框文本作用
ActionChains(self.driver).double_click(element).perform()
element.send_keys("tao")