Foreword
When using selenium do UI Automation and found that some of the input box on the pop-up window, enter the text, using the clear () method is invalid.
This will lead to the input again, after input string is not empty, but followed behind a long list of inputs, resulting in inaccurate results.
After several attempts, first click () Click the input box, and then enter, or found invalid, the final the following two ways to solve
- After using Double-click the input box, select all the text and then enter it
- Clear text input box using js
Problem Description
On some pop-up page, enter text input box, input can be normal, like the first time I enter test data: yoyo
Second, I want to change the test data, the first clear, then enter the text: lengthy
Results clear the text box is not valid, the input character string is accumulated twice
Method 1: double-clicking the input box
Double-click the first packaging element method writes base.py file
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
import time
class Base():
# # 作者:上海悠悠,QQ交流群:750815713
def __init__(self, driver):
self.driver = driver
def find(self, locator):
'''查找元素,loctor = ("id", "kw")'''
element = WebDriverWait(self.driver, 30, 1).until(EC.presence_of_element_located(locator))
return element
def click(self, locator):
'''点击元素'''
self.find(locator).click()
def double_click(self,locator):
'''双击事件'''
element = self.find(locator)
ActionChains(self.driver).double_click(element).perform()
def send(self, locator, text):
'''发送文本'''
self.find(locator).send_keys(text)
Run the code
# 作者:上海悠悠,QQ交流群:750815713
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
baidu = Base(driver)
# 输入框
loc = ("id", "kw")
baidu.send(loc, "yoyo")
time.sleep(3)
# 方法一:双击
baidu.double_click(loc)
# 重新输入
baidu.send(loc, "上海-悠悠")
After double-clicking, not empty, re-enter it
Method 2: JS clear the text box
The second solution ideas, you can use universal js, pit encountered as long as selenium, can be used to solve js.
# 作者:上海悠悠,QQ交流群:750815713
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
baidu = Base(driver)
# 输入框
loc = ("id", "kw")
baidu.send(loc, "yoyo")
time.sleep(3)
# # 方法一:双击
# baidu.double_click(loc)
# # 重新输入
# baidu.send(loc, "上海-悠悠")
# 方法二:万能的js
js = 'document.querySelector("#kw").value="";'
driver.execute_script(js)
baidu.send(loc, "上海-悠悠")
The method is better than multi-issue, a problem, do not always go to solve why not clear (), a change in thinking can always find a solution!