Python爬取微信好友的信息

最近在学习python的过程中发现了一些比较好玩的东西———-爬取微信好友的信息,并可以制作一些酷炫的效果,比如:统计微信好友男女比例、实现图灵机器人自动回复消息、抓取好友头像并拼接成图、获取好友签名信息并制作成云图等。

安装itchat

itchat是一个开源的微信个人接口,首先我们先安装itchat
方法一:可以使用本命令安装itchat

pip install itchat

方法二(适用于PyCharm):

通过此路径:File--->Settings----> Project Interpreter----> +  搜索itchat安装即可

图灵机器人自动回复消息

如果下面的 apikey无法使用的话,可在图灵机器人官网(http://www.tuling123.com/)自己注册一个

import requests
import itchat

apikey = '1841f627d8924f5ba0bb9ca12e76ad71'

# 定义机器人得到消息并获取回复内容的函数
def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key' : apikey,
        'info': msg,
        'userid' : 'wechat-robot'
    }
    try :
        r = requests.post(apiUrl,data).json()
        # 字典里的get方法在没有“text”值的时候会返回None,而不会抛出异常
        return r.get('text')
    except :
        # 如果服务器没能正常交互(返回非json或无法来连接),那么return None
        return

# 定义机器人回复的函数
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 为了保证apikey出现问题时仍旧可以恢复,这里设置一个默认的回复
    defaultReply = 'I received : '+ msg['Text']
    # 如果apikey出现问题,那么reply将会是None
    reply = get_response(msg['Text'])
    # a or b 的意思是:如果a有内容,那么返回 a,否则返回 b
    return reply or defaultReply

# 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动
itchat.auto_login(hotReload=True)
itchat.run()

统计微信好友男女比例

import itchat
import matplotlib.pyplot as plt 
# 登录方法,会弹出二维码,用微信扫描登录
itchat.auto_login()
friends = itchat.get_friends(update=True)

#统计好友的性别,微信中男性为1,女性为2,未知为0
def sex(friends):
    total_friends = len(friends)
    male =  female = other = 0
    for friend in friends:
        sex = friend['Sex']
        if sex == 1:
            male = male + 1
        elif sex == 2:
            female = female + 1
        else:
            other = other + 1
    sex_list = ["男生","女生","不明性别"]
    sex_number_list = [male,female,other]
    # 此行代码用来设置中文
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title(friends[0]['NickName'] +'微信中的男女比例')
    plt.bar(range(len(sex_list)),sex_number_list,tick_label=sex_list,color="yellow")
    plt.show()
    print("男性好友 : ", male)
    print("女性好友 : ", female)
    print("不明性别好友 : ", other)
    print("好友总数 ; ", total_friends)

# 调用函数sex()
sex(friends)

抓取好友头像并拼成图

import itchat
import os
from os import listdir
import math
import PIL.Image

itchat.auto_login()
friends = itchat.get_friends(update=True)
user = friends[0]["NickName"]
print(user)

# 建立文件夹来装好友的头像----- mkdir()方法用来创建文件夹(目录)
os.mkdir(user)

# 将头像存到一个文件夹下
number = 0
for friend in friends:
    img = itchat.get_head_img(userName=friend["UserName"])
    fileImage = open(user + "/" + str(number) + ".jpg",'wb')
    fileImage.write(img)
    fileImage.close()
    number += 1

# listdir()方法用于返回指定文件夹下包含的文件或文件夹的名字的列表,在此处就是:每一张图片的名字
pics = listdir(user)
# 获取照片的张数
numberPics = len(pics)
# 设置每张照片的大小
eachsize = int(math.sqrt(float(640*640)/numberPics))
# 获取每一行放置多少张图片
numbline = int(640/eachsize)
# 设置图片的大小为 640*640
toImage = PIL.Image.new("RGBA",(640,640))

x = 0
y = 0
# pic 为每一张图片
for pic in pics:
    try:
        # 打开图片
        img = PIL.Image.open(user + "/" + pic)
    except IOError:
        print("Error : 没有找到文件或读取文件失败")
    else:
        # 缩小图片 && ANTIALIAS(抗锯齿)
        img = img.resize((eachsize,eachsize),PIL.Image.ANTIALIAS)
        #拼接图片 paste()方法,粘贴图片,在拼接图片时将图片一张张粘贴上去
        toImage.paste(img, (x * eachsize,y * eachsize))
        x += 1
        if x == numbline:
            x = 0
            y += 1

# 保存拼接后的抬头像
toImage.save(user + ".BMP")
# 将拼接好的图片发送给文件传输助手
itchat.send_image(user + ".BMP" , 'filehelper')

获取好友签名信息并制作成云图

import itchat
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
import re

# 设置登录方法
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)

# 获取好友签名信息并储存在 siglist 中
siglist = []
for indedx,friend in enumerate(friends):
    sigture = friend['Signature']
    # 如果存在签名的话
    if len(friend['Signature']) > 0:
        # 将个性签名中的表情符号去掉(这里没有去除干净,利用正则表达式)
        sigture = sigture.replace('span','').replace('class','').replace('emoji','').replace('< =','').replace('"','').replace('</>','').replace('>','')
        siglist.append(sigture)

# 将siglist中的元素拼接为一个字符串
text = ''.join(siglist)

# jieba(结巴分词:有全模式、精确模式、默认模式、新词识别、搜索引擎模式)
# jieba.cut()所接收的两个参数,第一个参数为需要分词的字符串,第二个为是否采用全模式
word_list = jieba.cut(text, cut_all=True)
# 空格拼接
word_space_split = ' '.join(word_list)
# 字体的颜色为对应路径的背景图片的颜色
coloring = np.array(Image.open("D:/PythonWorkplace/WeChat/image.png"))
# font_path: 字体路径;  random_state: 为每个字体返回一个PIL颜色;  scale:按照比例放大画布;max_font_size:显示的最大字体的大小
# 如果参数 mask 为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代
my_wordcloud = WordCloud(background_color="white", max_words=2000,
                         mask=coloring, max_font_size=150, random_state=42, scale=3,
                         font_path="C:/Windows/Fonts/simkai.ttf").generate(word_space_split)
# 画布的颜色
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

猜你喜欢

转载自blog.csdn.net/A_D_I_D_A_S/article/details/81838865