Python3——模拟键鼠输入2

之前用PyUserInput中的PyMouse和PyKeyboard来模拟键鼠。除此之外还可以使用pynput模块,更加方便。
记录一些常用方法。

模拟鼠标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pynput.mouse import Button, Controller
 
mouse = Controller()
 
# 获取当前鼠标坐标
print('The current pointer position is {0}'.format(
    mouse.position))
 
# 设置鼠标坐标
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))
 
# 将鼠标从当前
mouse.move(5, -5)
 
# 按下和松开
mouse.press(Button.left)
mouse.release(Button.left)
 
#鼠标点击,可以设置次数
mouse.click(Button.left, 2)
 
#鼠标滚轮,可以左右、上下滚动。
mouse.scroll(0, 2)

模拟键盘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from pynput.keyboard import Key, Controller
 
keyboard = Controller()
 
#按下与松开由Key键导入的特殊按钮
keyboard.press(Key.space)
keyboard.release(Key.space)
 
#按下与松开小写字符
keyboard.press('a')
keyboard.release('a')
 
#按下与松开大写字符
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')
 
#键入字符串,可以键入中文字符
keyboard.type('Hello World')

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注