pyautogui自动化工具使用

为了处理一些琐碎的事情,测试了一下pyautogui的功能,实现的功能是给指定的微信好友发送指定信息。这
里并没有用微信的api直接发送,而是通过模拟真实的操作来实现的,主要是了解一些自动化工具的使用。
这里使用的是python的pyautogui库。
主要功能是自动打开电脑版微信,搜索指定好友,打开好友对话框,输入文本并发送。

以下是实现代码

# Import necessary libraries
import pyautogui
import time

# Locate WeChat icon on the taskbar and click it
wechat_icon = pyautogui.locateOnScreen('image/wechat_icon.png', confidence=0.9)

pyautogui.doubleClick(wechat_icon)
time.sleep(3)

# Wait for WeChat to open
# Locate the search bar and click it
search_bar = pyautogui.locateOnScreen('image/search_bar.png', confidence=0.9)
pyautogui.click(search_bar)
time.sleep(2)

# Type the name of the friend to send message to
pyautogui.typewrite("name")
pyautogui.press('enter')
# Wait for search results to load
time.sleep(2)

# Click on the friend's name in the search results
friend_name = pyautogui.locateOnScreen('image/name.png', confidence=0.9)
pyautogui.doubleClick(friend_name)

# Wait for the chat window to open
time.sleep(2)

# Type the message to send
pyautogui.typewrite('Hello, SX!')

# Press Enter to send the message
pyautogui.press('enter')

大部分人都介绍过pyautogui的api,这里不再赘述了。这里主要说明一下实操需要注意的点。

1:Pyautogui找图的api里面的图片地址是什么?

wechat_icon = pyautogui.locateOnScreen('image/wechat_icon.png', confidence=0.9)

即这个’image/wechat_icon.png’是什么东西,从哪里来的?

在这里插入图片描述
如上图所示,image/wechat_icon.png其实就是图片的地址,这个图是一个桌面截图,你可以通过其他工具把对应的图标截取下来,然后pyautogui会从你屏幕上找这个图片。
**这里很坑的一点是,截图必须和找的图一模一样,不然都找不到,即你截了图,然后把这个图标挪了个位置,那不好意思了,大概率是找不到了,往大了说,这种方式你换台电脑即便有这个应用也找不到,当然也不是没有解决的方案,比如你打开的微信,微信上面的搜索框是一样的,无论你把窗口怎么拖,只要输入框在,就能找到。也可以通过指定位置来模拟点击pyautogui.click(100,100) **

2:Pyautogui输入不了中文

//这两个方法不支持输入中文
pyautogui.write()
pyautogui.typewrite()

可以通过以下方式替代

pyperclip.copy('中国')
pyperclip.paste() 

以上。

猜你喜欢

转载自blog.csdn.net/qq_39860954/article/details/129988432