Python Automatically Collects WeChat Contacts

The epidemic has finally improved. Thanks to all the white-clothed angels who are fighting for it, you are the best!Fabulous!

The white-clothed angels are fighting on the front line, and we can't always lie down at home to make contributions. We should also strengthen our study and strive for a good job in the spring:

 

 

This week, I spent a few days reviewing Python's pywinauto-related usage and a bunch of library functions to find that the library is still very powerful.

  • What is pywinauto?

pywinauto is a set of python modules for automating Windows GUI.Simply put, it allows you to send mouse and keyboard actions to windows dialogs and controls.This is the official explanation, in short, that you can use python code to manipulate desktop programs.

  • install
pip install pywinauto
  • Use

The way pywinauto is used is simple, but it provides a large number of functions that operate on GUI interface elements that need to be slowly understood.

The official documentation is complete: https://pywinauto.readthedocs.io/

Beginner-level details aside, you can not read the official English, you can also go online to search, a large number of introductory documents.

Let's go directly to today's topic: Collect WeChat contacts in Python, start with program execution effect video:

 

Procedural principles

(1) First WeChat should be opened and logged in successfully.Get the process ID of the current WeChat:

    PID=0
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid','name'])
        except psutil.NoSuchProcess:
            pass
        else:
            if 'WeChat.exe' == pinfo['name']:
                PID = pinfo['pid']

(2) Connect to this process using pywinauto:

    app = Application(backend='uia').connect(process=PID)
    win = app[u'WeChat']

(3) Find the location of the Address Book button on the left and click the mouse:

    addresslist = win.child_window(title=u"Mail list", control_type="Button")
    addresslist.draw_outline()
    cords =  addresslist.rectangle()
    pywinauto.mouse.click(button='left', coords=(cords.left + 10, cords.top+10))
    win.draw_outline()

(4) Core code, by calling down keyboard instructions, opens contact details page by page, according to the page structure of details page, all data in the page: nickname, notes, region, micro-signal, source.

    #Contacts
    con_list = win.child_window(title=u"Contacts", control_type="List")
    pywinauto.mouse.click(button='left', coords=(cords.left + 100, cords.top+10))
    data = []
    while True:
        con_list.type_keys("{DOWN}")
        rect_edit = win.Edit2.rectangle()
        #Find contact details page
        if rect_edit.left > cords.left + 300:
            #Whole panel 
            page = {u'Nickname':'',u'Remarks':'',u'Region':'',u'Wechat number':'',u'Source':''}
            #Nickname
            win.Edit2.draw_outline()
            page[u'Nickname'] = win.Edit2.get_value()
            #Detail page elements are not fixed and cannot be retrieved by control sequence number
            static_wxh = win.child_window(title=u"Wechat number", control_type="Text")
            Pane46 = static_wxh.parent().parent()
            for item in Pane46.children():
                item.draw_outline()
                lines = item.children()
                key = lines[0].window_text()
                value = lines[1].window_text()
                page[key] = value
            data.append(page)
            #Stop at last contact
            if len(data) >2 and data[-2][u'Wechat number'] == data[-1][u'Wechat number']:
                data.remove(data[-1])
                saveTxt(data)
                break

The fourth step of the method has been optimized several times before and after. This is the final optimized version. This version is the fastest among the various solutions and the best compatibility method. If any friend has a better solution, please leave a message to discuss!

The complete code is attached below:

#coding=gbk
'''
Created on 
@author: Administrator
'''
import psutil
import pywinauto
from pywinauto.application import Application
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def getWinxin():
    PID=0
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid','name'])
        except psutil.NoSuchProcess:
            pass
        else:
            if 'WeChat.exe' == pinfo['name']:
                PID = pinfo['pid']
    app = Application(backend='uia').connect(process=PID)
    win = app[u'WeChat']
    addresslist = win.child_window(title=u"Mail list", control_type="Button")
    addresslist.draw_outline()
    cords =  addresslist.rectangle()
    pywinauto.mouse.click(button='left', coords=(cords.left + 10, cords.top+10))
    win.draw_outline()
    
    #Contacts
    con_list = win.child_window(title=u"Contacts", control_type="List")
    pywinauto.mouse.click(button='left', coords=(cords.left + 100, cords.top+10))
    data = []
    while True:
        con_list.type_keys("{DOWN}")
        rect_edit = win.Edit2.rectangle()
        #Find contact details page
        if rect_edit.left > cords.left + 300:
            #Whole panel 
            page = {u'Nickname':'',u'Remarks':'',u'Region':'',u'Wechat number':'',u'Source':''}
            #Nickname
            win.Edit2.draw_outline()
            page[u'Nickname'] = win.Edit2.get_value()
            #Detail page elements are not fixed and cannot be retrieved by control sequence number
            static_wxh = win.child_window(title=u"Wechat number", control_type="Text")
            Pane46 = static_wxh.parent().parent()
            for item in Pane46.children():
                item.draw_outline()
                lines = item.children()
                key = lines[0].window_text()
                value = lines[1].window_text()
                page[key] = value
            data.append(page)
            #Stop at last contact
            if len(data) >2 and data[-2][u'Wechat number'] == data[-1][u'Wechat number']:
                data.remove(data[-1])
                saveTxt(data)
                break
def saveTxt(data):
    with open("data.txt",'ab') as f:
        f.write(u'Wechat number,Remarks,region,source,Nickname\r\n')
        for item in data:
            f.write('%s,%s,%s,%s,%s\r\n' % (item[u'Wechat number'],item[u'Remarks'],item[u'Region'],item[u'Source'],item[u'Nickname']))
    os.system('notepad.exe data.txt')
if __name__ == '__main__':
    getWinxin()

 

Two original articles have been published. 6. 10,000 visits+
Private letter follow

Tags: Python Windows Spring pip

Posted on Sat, 22 Feb 2020 21:17:25 -0500 by syam92