您的位置:首页 > 编程语言 > Python开发

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

2017-09-17 20:15 411 查看

前言

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

安装
itchat

笔者使用
pip
工具包进行安装,
pip install itchat


安装完毕后 试着进入python写入
import itchat
,没有任何提示说明安装成功。

统计微信好友男女比例

#-*- coding:utf-8 -*-
#导入需要使用的相关模块
import itchat
import re
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import numpy as np
import PIL.Image as Image
from os import path
from 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 +=1

total = 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 itchat
import os
import PIL.Image as Image
from os import listdir
import 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 += 1

pics = 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 = 0
y = 0

for 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 requests
import itchat
from 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 busy

itchat.auto_login(hotReload=True)
itchat.run()


总结

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

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

itchat开发文档:http://itchat.readthedocs.io/zh/latest/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 微信