模拟键盘按键操作的方法:
1.win32api
2.SendKeys
3.WebElement对象的send_keys()方法
4.ActionChains类提供了几个模拟按键的方法
以ActionChains为例演示输入文本、输入空格、删除:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
class TestActionChains():
def setup(self):
self.driver = webdriver.Chrome()
# 隐式等待
self.driver.implicitly_wait(5)
self.driver.get('https://sahitest.com/demo/label.htm')
def teardown(self):
self.driver.quit()
def test_keys(self):
self.driver.find_element(By.XPATH, '/html/body/label[1]/input').click()
action = ActionChains(self.driver)
# 输入username
action.send_keys("username").pause(1)
# 输入空格
action.send_keys(Keys.SPACE).pause(1)
# 输入zz
action.send_keys('zz').pause(1)
# 键盘删除
action.send_keys(Keys.BACK_SPACE).perform()
sleep(5)