【实例】Python爬取微信好友男女比例

本文介绍了一个使用Python进行微信好友性别比例分析的小项目。通过itchat登录微信并获取好友列表,统计男性、女性及未标记性别的好友数量,并利用matplotlib绘制饼图展示各性别占比。

一、环境

python 3.6.5

二、操作

# 导入itchat模块
import itchat
# 导入pyplot子库
import matplotlib.pyplot as plt

# 定义parse_friend循环,提取男女信息数据并存入text字典
def parse_friens():
    itchat.login()
    text = dict()
    friends = itchat.get_friends(update=True)[0:]
    print(friends)
    male = "male"
    female = "female"
    other = "other"
    #遍历获取男女人数保存到text
    for i in friends[1:]:
        sex = i['Sex']
        if sex == 1:
            text[male] = text.get(male,0) + 1
        elif sex == 2:
            text[female] = text.get(female,0) + 1
        else:
            text[other] = text.get(other,0) + 1
            
# 好友总人数
    total = len(friends[1:])
    print("A total of " + str(total) + " friends of your WeChat friends")
    print( "Male friends: %.2f%%" % (float(text[male])/ total*100) + "\n" +
           "Female friends: %.2f%%" % (float(text[female]) / total * 100) + "\n" +
           "Unidentified sex: %.2f%%" % (float(text[other]) / total * 100 ) )
    # 通过draw()函数汇出柱状图
    draw(text)
    
# 定义绘出好友柱状图函数
def draw(datas):
    for key in datas.keys():
        plt.bar(key,datas[key])
    plt.legend()
    plt.xlabel('sex')
    plt.ylabel('rate')
    plt.title("Gender of Alfred's friends")
    plt.show()
parse_friens()

三、效果图

这里写图片描述

Python爬取微信朋友圈有多种方法,但各有优缺点: 1. **使用itchat包实现PC端网页版微信登录爬取数据**:此方法已不可用,因为微信已经关闭网页版 [^1]。 2. **使用pywinauto库在PC端微信爬取数据**:需要安装psutil和pywinauto库,以下是示例代码: ```python import psutil import pywinauto from pywinauto.application import Application PID = 0 print("获取微信进程id") for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: print("没有打开微信") pass else: if 'WeChat.exe' == pinfo['name']: PID = pinfo['pid'] print("找到微信进程") print("用PyWinAuto 实例化一个应用") app = Application(backend='uia').connect(process=PID) print("打开微信朋友圈") win = app['微信'] pyq_btn = win.child_window(title="朋友圈", control_type="Button") cords = pyq_btn.rectangle() pywinauto.mouse.click(button='left', coords=(cords.left + 10, cords.top + 10)) print("打开微信朋友圈完成") pyq_win = app['朋友圈'] print(pyq_win.dump_tree()) ``` 操作步骤为:先打开电脑微信并最大化,再运行程序。不过,Pywinauto库在2019年之后未再维护,很多模块不兼容win11 [^1][^2]。 3. **调用API**:这种方式最方便,但微信官方并不提供朋友圈数据接口,最后得到的数据只有通讯录内容 [^1]。 4. **使用Appium自动化模拟操作数据**:Appium不是一个库,是一套软件,安装需要Java环境等,还有配置,非常麻烦。不过利用Appium可以做到App的可见即可,也能实现自动化驱动和数据爬取,但实际运行后,其解析比较烦琐,且容易发生重复和中断。若将mitmdump和Appium结合,让mitmdump监听App数据实时处理,Appium只负责自动化驱动,可提高爬取和解析效率 [^1][^5]。 5. **使用uiautomator2库自动化模拟人工操作**:uiautomator2比Appium简单易上手,但是目前相关代码较少 [^1]。 6. **代码实现进入朋友圈页面**:登录完成之后,进入朋友圈的页面。选中朋友圈所在的选项卡,点击朋友圈按钮,即可进入朋友圈,代码如下: ```python def enter(self): # 选项卡 tab = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/bw3"][3]'))) tab.click() # 朋友圈 moments = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/atz'))) moments.click() ``` [^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

風月长情

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

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

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

打赏作者

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

抵扣说明:

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

余额充值