1. 键盘操作需要通过send_keys()方法来进行输入内容
2. 输入的内容可以根据用户需求指定输入键盘所有按键
3. 键盘的操作需要结合导入Keys类来进行使用
常用操作:
1. 删除键(BackSpace):send_keys(Keys.BACK_SPACE)
2. 空格键(Space):send_keys(Keys.SPACE)
3. 制表键(Tab):send_keys(Keys.TAB)
4. 回退键(Esc):send_keys(keys.ESCAPE)
5. 回车键(Enter):send_keys(Keys.ENTER)
6. Ctrl+A:send_keys(Keys.CONTROL,'a')
7. Alt+C:send_keys(Keys.ALT,'c')
8. Alt+V:send_keys(Keys.ALT,'v')
9. 按下某个键盘上的键:key_down(value, element=None)
10.松开某个键:key_up(value, element=None)
11.键盘右键:send_keys(Keys.RIGHT)
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import Keys, ActionChains
driver = webdriver.Chrome()
url = "https://www.baidu.com/"
driver.get(url)
driver.maximize_window ()
# 输入框:<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
# 百度一下:<input type="submit" id="su" value="百度一下" class="bg s_btn">
element = driver.find_element(By.XPATH, '//*[@id="kw"]')
element.send_keys('11112')
sleep(2)
# 回退键(Esc):send_keys(keys.ESCAPE)
element.send_keys(Keys.ESCAPE)
sleep(2)
# 回车键(Enter):send_keys(Keys.ENTER)
element.send_keys(Keys.ENTER)
# 删除键(BackSpace):send_keys(Keys.BACK_SPACE)
element.send_keys(Keys.BACK_SPACE)
sleep(2)
# 空格键(Space):send_keys(Keys.SPACE)
element.send_keys(Keys.SPACE)
sleep(2)
# 制表键(Tab):send_keys(Keys.TAB)
element.send_keys(Keys.TAB)
# Ctrl+A:send_keys(Keys.CONTROL,'a')
element.send_keys(Keys.CONTROL,'a')
sleep(2)
# Alt+C:send_keys(Keys.ALT,'c')
element.send_keys(Keys.CONTROL,'c')
sleep(2)
# 键盘右键:send_keys(Keys.RIGHT)
element.send_keys(Keys.RIGHT)
sleep(2)
# Alt+V:send_keys(Keys.ALT,'v')
element.send_keys(Keys.CONTROL,'v')
# 按下某个键盘上的键:key_down(value, element=None)
# 松开某个键:key_up(value, element=None)
# value:要发送的修饰键。在Keys类中定义。
# element:发送密钥的元素。如果没有,则向当前聚焦的元素发送一个键
# 只能与修饰键(Control、Alt 和 Shift)一起使用
# 构造ActionChains对象:ActionChains(driver)
# perform()执行所有存储的操作
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
sleep(5)
driver.quit()