怎么用Python提取PC微信通讯录信息?

By | 2022-03-01

这里用到了uiautomation模块

中文说明

实现代码:

import uiautomation as auto
import csv,codecs

result = []
wechat_str=""

wechatWindow = auto.WindowControl(searchDepth=1, Name="微信", ClassName='WeChatMainWndForPC')
wechatWindow.SetActive()
txl_btn = wechatWindow.ButtonControl(Name='通讯录')
txl_btn.Click()
contacts=wechatWindow.ListControl(Name="联系人")
contacts.GetChildren()[6].Click()
send_msg=wechatWindow.ButtonControl(Name='发消息')
detail=send_msg.GetParentControl()
result.append(["昵称", "备注", "地区", "微信号"])

for i in range(1,5000):
    try:
        nickname=detail.GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren()[0].Name
        remark=detail.GetChildren()[2].GetChildren()[0].GetChildren()[1].Name
        address=detail.GetChildren()[2].GetChildren()[1].GetChildren()[1].Name
        wechat=detail.GetChildren()[2].GetChildren()[2].GetChildren()[1].Name

        if wechat+"," in wechat_str:
            break
            pass
        wechat_str+=wechat+","
        result.append([nickname, remark,address, wechat])
        contacts.SendKeys("{DOWN}")
        pass
    except:
        pass
        contacts.SendKeys("{DOWN}")
        continue
    pass

file_csv = codecs.open("通讯录.csv",'w+','utf-8-sig')
writer = csv.writer(file_csv, delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
for data in result:
    writer.writerow(data)
print("保存文件成功,处理结束")

如果中文乱码需将utf-8改为utf-8-sig
(代码是简单demo没有优化,请自行优化)

我这里用的 窗口元素识别工具是 FlaUInspect

FlaUInspect可以看到所有元素位置都很清楚,此外还可以用官方的组件元素识别工具,inspect.exe,这里就不多说。

运行完毕可以看到通讯录表格已经被保存下来了。速度还可以。