Python自动化学习:pyautogui, keyboard 使用

本文介绍了Python的pyautogui库和keyboard库,用于实现自动化操作。pyautogui提供了获取鼠标位置、模拟键盘输入和鼠标点击等功能,而keyboard库则可以监听键盘事件并模拟按键。通过这两个库,可以实现如通过空格键获取鼠标位置等自动化任务。文中给出了详细代码示例,帮助读者理解如何使用这两个库进行自动化操作。
摘要由CSDN通过智能技术生成

pyautogui

官方文档速览
https://pyautogui.readthedocs.io/en/latest/index.html
在这里插入图片描述

获取鼠标位置

能够实现下面功能:

  • 获取当前鼠标的坐标信息
import pyautogui as pg

pos = pg.position()
print(pos.x,pos.y)

键盘相关

  • 模拟字符串输入
pg.typewrite("hello")
pg.press('1') # 模拟键盘键入
  • 程序睡眠指定的时间,类似于 time.sleep()
pg.sleep(10)
print("hello")

鼠标相关

  • 模拟鼠标操作:移动鼠标
pg.moveTo((35,50))
pg.click() # 鼠标点击

在这里插入图片描述

通过图片定位位置

'''遮挡住图标不行,用扩展屏幕也不行'''
pos = pg.locateAllOnScreen("./img.png")
for p in pos:
    print(p)
D:\Anaconda3\envs\data\python.exe G:/Gait_Reproduce/t.py
Box(left=1277, top=368, width=90, height=58)

Process finished with exit code 0

在这里插入图片描述

参考页面
https://www.jianshu.com/p/8e508c6a05ce
https://www.pianshen.com/article/7555171409/

keyboard

专门的 API 文档如下:
https://github.com/boppreh/keyboard#api

能够实现下述功能:

  • 监听键盘某个键是否按下从而产生事件
while True:
    if k.is_pressed('enter'):
        print("1 is pressed")
  • 等待某个键按下之后再操作后面的代码
    当 “1” 按下之前,不会运行下面的 “hello” 代码
k.wait('1')
print("hello")
  • 模拟键盘按下某个值
while True:
    k.press('1')
  • 全局监听某些操作,并作出反应:
'''首先确定一个事件,通过这个事件来触发内容'''
event = k.KeyboardEvent("down",123,'space')
'''通过一个函数来指定处理策略,这个传入的 x 的类型就是一个 KeyboardEvent 对象,所以要与我们设定的这个对象进行匹配'''
def reply_press(x):
    if x.event_type == event.event_type and x.name == event.name:
        print("pressed down the space")
'''通过 hook 操作,将这些针对某个事件的响应操作 “挂到” 键盘上'''
k.hook(reply_press)
'''等待事件触发,但是后面写的代码内容阻塞住不执行,如果不想让程序阻塞的话,可以不使用 wait'''
# k.wait()

for i in range(100):
    time.sleep(0.5)
    print(i)
'''不使用 wait 后面的程序会依次执行,过程中 hook 指定的响应操作也有效,例如'''

0
1
2
pressed down the space
3
4
5
6
7
8
 pressed down the space
9
10
11
12
pressed down the space
 13
14
15
 pressed down the space
16

Process finished with exit code -1

小训练

  • 通过 keyboard 和 pyautogui 库实现一个小功能:
    • 通过空格来不断获取鼠标所处位置的值
    • 不输入空格的时候不获得鼠标位置
      写法1:
while True:
    if k.is_pressed('space'):
        pos = pg.position()
        print(pos.x,pos.y)
        

写法2:

def generate_position(x):
    event = k.KeyboardEvent("down",190,'space')
    if x.event_type == event.event_type and x.name == event.name:
        pos = pg.position()
        print(pos.x,pos.y)

k.hook(generate_position)

for i in range(100):
    pg.sleep(1)
    print(i)
0
1
 2682 622
2
3
4
5
6
3516 254
 7
8
9
 2668 1015
10
11
 2668 1015
12
13
3030 559
 14
15

Process finished with exit code -1
  • 0
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暖仔会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值