用法:
element=driver.find_element_by_xpath(xpath)
element.send_keys(content)
遇到特殊的控件,如:
控件默认值为1,直接使用send_keys会在“1”后面继续插入值。
可以使用ActionChains解决。
action=ActionChains(driver)
action.move_to_element(element)
action.double_click() #双击选中当前文字
action.send_keys(content)
action.perform() #执行action,必须加上这个
使用send_keys有时会碰到文字只输入一半的情况,不知原因,可能是速度太快,这里可以使用WebDriverWait判断一下:
def send_message(driver,xpath,content,num=3): #判断文字是否写全,最多尝试num次
element=driver.find_element_by_xpath(xpath)
element.clear() #考虑到可能反复尝试写入文字,每次写入前清空一次文本框
element.send_keys(content)
try:
WebDriverWait(driver,5).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,xpath),content))
return 1
#使用WebDriverWait判断文本框中的内容是否与content一致,不一致进入except。
except:
if num>0:
return send_message(driver,xpath,content,num-1)
#尝试3次
else:
print('input failed ',content)
return 0 #三次后仍不行返回输入失败