使用pywinauto爬取微信通讯录
1.前期准备
将微信窗口固定到这个位置,即通讯录第一个人的显示
2.运行如下代码并将鼠标焦点到微信窗口
import psutil
import pywinauto
from pywinauto.application import Application
import os
import sysdef getWinxin():PID=0for proc in psutil.process_iter():try:pinfo = proc.as_dict(attrs=['pid','name'])except psutil.NoSuchProcess:passelse:if 'WeChat.exe' == pinfo['name']:PID = pinfo['pid']app = Application(backend='uia').connect(process=PID)win = app[u'微信']addresslist = win.child_window(title=u"通讯录", control_type="Button")addresslist.draw_outline()cords = addresslist.rectangle()pywinauto.mouse.click(button='left', coords=(cords.left + 10, cords.top+10))win.draw_outline()#联系人con_list = win.child_window(title=u"联系人", control_type="List")pywinauto.mouse.click(button='left', coords=(cords.left + 100, cords.top+10))data = []while True:rect_edit = win.Edit2.rectangle()#找到联系人详情页if rect_edit.left > cords.left + 300:pagetube=[]try:win.Edit2.draw_outline()pagetube.append(win.Edit2.get_value())except:print('no edit2')try:win.Edit3.draw_outline()pagetube.append(win.Edit3.get_value())except:print('no edit3')try:win.Edit4.draw_outline()pagetube.append(win.Edit4.get_value())except:print('no edit4')try:win.Edit5.draw_outline()pagetube.append(win.Edit5.get_value())except:print('no edit5')try:win.Edit6.draw_outline()pagetube.append(win.Edit6.get_value())except:print('no edit6')print(pagetube )data.append(pagetube)#最后一个联系人时停止if len(data) >2 and data[-2][0] == data[-1][0]:data.remove(data[-1])saveTxt(data)breakcon_list.type_keys("{DOWN}")
def saveTxt(data):with open("data.txt",'a',encoding="utf-8") as f:for item in data:f.write(str(item)+'\n')
if __name__ == '__main__':getWinxin()
3.运行一段时间后观察data.txt