【Python】利用python爬取微信朋友info

来源:互联网 发布:张一山 演技 知乎 编辑:程序博客网 时间:2024/06/15 04:26

前言

今天在工作室学习时,偶然被某公众号推送了《我用python爬了爬自己的微信朋友》,因为本身也是在学习python的过程,索性就中断了手头的工作,点进去看,并操作了一番,学习了itchat模块,并查阅了相关资料做了一些拓展学习。

安装itchat

笔者使用pip工具包进行安装,pip install itchat
安装完毕后 试着进入python写入import itchat,没有任何提示说明安装成功。

统计微信好友男女比例

#-*- coding:utf-8 -*-#导入需要使用的相关模块import itchatimport reimport jiebaimport matplotlib.pyplot as pltfrom wordcloud import WordCloud,ImageColorGeneratorimport numpy as npimport PIL.Image as Imagefrom os import pathfrom scipy.misc import imread   #登录方法,会弹出登录二维码,用微信扫描登录itchat.auto_login()     #关于所有微信还有的资料信息都封装在这个方法里friends = itchat.get_friends(update=True)[0:] #获取好友性别信息male = female = other = 0#遍历好友信息for i in friends[1:]:    #按照微信资料上的信息规则,男1,女2,其他3    sex = i['Sex']    if sex == 1:        male += 1    elif sex == 2:        female +=1    else:        other +=1total = len(friends[1:])print('男生好友:%.2f%%' % (float(male)/total*100) + '\n' +'女生好友:%.2f%%' % (float(female)/total*100) + '\n' +'不明性别好友:%.2f%%' % (float(other)/total*100) + '\n' )

抓取好友头像并拼成图

# -*- coding:utf-8 -*-#导入相关模块import itchatimport osimport PIL.Image as Imagefrom os import listdirimport math#登录itchat.auto_login(enableCmdQR=True)#获取微信全部好友的信息friends = itchat.get_friends(update=True)[0:]#获取自己的用户名user = friends[0]["UserName"]#打印用户名print(user)#建立文件夹用来装好友的头像os.mkdir(user)num = 0#遍历好友信息,将头像保存for i in friends:    img = itchat.get_head_img(userName=i["UserName"])    fileImage = open(user + "/" + str(num) + ".jpg",'wb')    fileImage.write(img)    fileImage.close()    num += 1pics = listdir(user)numPic = len(pics)print(numPic)eachsize = int(math.sqrt(float(640 * 640) / numPic))print(eachsize)numline = int(640 / eachsize)toImage = Image.new('RGBA', (640, 640))print(numline)x = 0y = 0for i in pics:    try:        #打开图片        img = Image.open(user + "/" + i)    except IOError:        print("Error: 没有找到文件或读取文件失败")    else:        #缩小图片        img = img.resize((eachsize, eachsize), Image.ANTIALIAS)        #拼接图片        toImage.paste(img, (x * eachsize, y * eachsize))        x += 1        if x == numline:            x = 0            y += 1#保存拼接后的头像toImage.save(user + ".BMP")itchat.send_image(user + ".BMP", 'filehelper')

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

#获取好友签名信息siglist = []#遍历好友信息for i in friends:    #过滤信息    signature = i['Signature'].strip().replace('span','').replace('class','').replace('emoji','')    rep = re.compile('1f\d+\w*|[<>/=]')    signature = rep.sub('',signature)    siglist.append(signature)#所有签名信息封装在text中text = ''.join(siglist)#写入本地文件textfile = open('info.txt','w')textfile.write(text)text_from_file_with_apath = open('./info.txt').read()wordlist = jieba.cut(text_from_file_with_apath, cut_all = True)word_space_split = " ".join(wordlist)#画图coloring = plt.imread('./haha.jpg')#设置词云相关属性my_wordcloud = WordCloud(background_color='white',                        max_words=2000,                        mask=coloring,                        max_font_size=100,                        random_state=42,                        font_path='/Library/Fonts/Microsoft/SimHei.ttf').generate(word_space_split)image_colors = ImageColorGenerator(coloring)#显示词云plt.imshow(my_wordcloud)plt.axis('off')plt.show()# 保存图片my_wordcloud.to_file(path.join(d, "签名.png"))

制作聊天机器人

#-*- coding=utf8 -*-#导入相关模块import requestsimport itchatfrom wxpy import *#此处*为图灵机器人的api key,需要到http://www.tuling123.com免费申请KEY = '***********************'def get_response(msg):    apiUrl = 'http://www.tuling123.com/openapi/api'    data = {        'key'    : KEY,        'info'   : msg,        'userid' : 'wechat-robot',    }    try:        r = requests.post(apiUrl, data=data).json()        return r.get('text')    except:        return#个人聊天专用       @itchat.msg_register(itchat.content.TEXT)#群聊专用#@itchat.msg_register('Text', isGroupChat = True)def tuling_reply(msg):    defaultReply = 'I received: ' + msg['Text']    reply = get_response(msg['Text'])    #返回机器人的聊天信息    return reply or defaultReply    #busy 的内容可自行更改,开启后就是只回复这条信息,需要打开return busy    #busy = '您好,该用户正在忙,稍后才能看到您的信息,如有急事请拨打该用户手机号码。'.decode('utf-8')    #return busyitchat.auto_login(hotReload=True)itchat.run()

总结

关于开头提到的那篇推文,推文所展示的制作词云图的功能似乎有些缺陷,运行后只展示了背景颜色,文字没有显示。在此篇文章中,修改了词云图的制作逻辑(应该说该复杂了),最后次云图便正常显示了。

今天学习到内容只是itchat模块的冰山一角,itchat模块中还有许多功能能被得到很好的使用。

itchat开发文档:http://itchat.readthedocs.io/zh/latest/

原创粉丝点击