itchat和matplotlib的结合使用爬取微信信息的实例


Posted in Python onAugust 25, 2017

前几天无意中看到了一片文章,《用 Python 爬了爬自己的微信朋友(实例讲解)》,这篇文章写的是使用python中的itchat爬取微信中朋友的信息,其中信息包括,昵称、性别、地理位置等,然后对这些信息进行统计并且以图像形式显示。文章对itchat的使用写的很详细,但是代码是贴图,画图使用R中的包画,我对着做了一遍,并且把他没有贴画图的代码做了一遍,画图是使用matplotlib。由于他没有贴代码,所以我把我写的贴出来供以后复制。

首先是安装itchat的包,可以使用清华大学的镜像:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple itchat

爬取微信好友男女比例:

import itchat
 
itchat.login()
friends=itchat.get_friends(update=True)[0:]
male=female=other=0
for i in friends[1:]:
 sex=i['Sex']
 if sex==1:
  male+=1
 elif sex==2:
  female+=1
 else:
  other+=1
   
total=len(friends[1:])
malecol=round(float(male)/total*100,2)
femalecol=round(float(female)/total*100,2)
othercol=round(float(other)/total*100,2)
print('男性朋友:%.2f%%' %(malecol)+'\n'+
'女性朋友:%.2f%%' % (femalecol)+'\n'+
'性别不明的好友:%.2f%%' %(othercol))
print("显示图如下:")

 画图:柱状图和饼状图,图片如下:

itchat和matplotlib的结合使用爬取微信信息的实例itchat和matplotlib的结合使用爬取微信信息的实例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
#解决中文乱码不显示问题
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体 
mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题 
 
map = {
 'Female': (malecol, '#7199cf'),
 'Male': (femalecol, '#4fc4aa'),
 'other': (othercol, '#e1a7a2')
}
 
fig = plt.figure(figsize=(5,5))# 整体图的标题
ax = fig.add_subplot(111)#添加一个子图
ax.set_title('Gender of friends')
 
xticks = np.arange(3)+0.15# 生成x轴每个元素的位置
bar_width = 0.5# 定义柱状图每个柱的宽度
names = map.keys()#获得x轴的值
values = [x[0] for x in map.values()]# y轴的值
colors = [x[1] for x in map.values()]# 对应颜色
 
bars = ax.bar(xticks, values, width=bar_width, edgecolor='none')# 画柱状图,横轴是x的位置,纵轴是y,定义柱的宽度,同时设置柱的边缘为透明
ax.set_ylabel('Proprotion')# 设置标题
ax.set_xlabel('Gender')
ax.grid()#打开网格
ax.set_xticks(xticks)# x轴每个标签的具体位置
ax.set_xticklabels(names)# 设置每个标签的名字
ax.set_xlim([bar_width/2-0.5, 3-bar_width/2])# 设置x轴的范围
ax.set_ylim([0, 100])# 设置y轴的范围
for bar, color in zip(bars, colors):
 bar.set_color(color)# 给每个bar分配指定的颜色
 height=bar.get_height()#获得高度并且让字居上一点
 plt.text(bar.get_x()+bar.get_width()/4.,height,'%.2f%%' %float(height))#写值
plt.show()
#画饼状图
fig1 = plt.figure(figsize=(5,5))# 整体图的标题
ax = fig1.add_subplot(111)
ax.set_title('Pie chart')
labels = ['{}\n{} %'.format(name, value) for name, value in zip(names, values)]
ax.pie(values, labels=labels, colors=colors)#并指定标签和对应颜色
plt.show()

爬取其他信息,对省份分类并根据个数对其排序

#用来爬去各个变量
def get_var(var):
 variable=[]
 for i in friends:
  value=i[var]
  variable.append(value)
 return variable
 
#调用函数得到各个变量,并把数据存到csv文件中,保存到桌面
NickName=get_var('NickName')
Sex=get_var('Sex')
Province=get_var('Province')
City=get_var('City')
Signature=get_var('Signature')
 
pros=set(Province)#去重
prosarray=[]
for item in pros:
 prosarray.append((item,Province.count(item)))#获取个数
def by_num(p):
 return p[1]
prosdsored=sorted(prosarray,key=by_num,reverse=True)#根据个数排序

画省份图:

itchat和matplotlib的结合使用爬取微信信息的实例

#画图
figpro = plt.figure(figsize=(10,5))# 整体图的标题
axpro = figpro.add_subplot(111)#添加一个子图
axpro.set_title('Province')
xticks = np.linspace(0.5,20,20)# 生成x轴每个元素的位置
bar_width = 0.8# 定义柱状图每个柱的宽度
pros=[]
values = []
count=0
for item in prosdsored:
 pros.append(item[0])
 values.append(item[1])
 count=count+1
 if count>=20:
  break
 
colors = ['#FFEC8B','#FFE4C4','#FFC125','#FFB6C1','#CDCDB4','#CDC8B1','#CDB79E','#CDAD00','#CD96CD','#CD853F','#C1FFC1','#C0FF3E','#BEBEBE','#CD5C5C','#CD3700','#CD2626','#8B8970','#8B6914','#8B5F65','#8B2252']# 对应颜色
 
bars = axpro.bar(xticks, values, width=bar_width, edgecolor='none')
axpro.set_ylabel('人数')# 设置标题
axpro.set_xlabel('省份')
axpro.grid()#打开网格
axpro.set_xticks(xticks)# x轴每个标签的具体位置
axpro.set_xticklabels(pros)# 设置每个标签的名字
axpro.set_xlim(0,20)# 设置x轴的范围
axpro.set_ylim([0, 100])# 设置y轴的范围
 
for bar, color in zip(bars, colors):
 bar.set_color(color)# 给每个bar分配指定的颜色
 height=bar.get_height()#获得高度并且让字居上一点
 plt.text(bar.get_x()+bar.get_width()/4.,height,'%.d' %float(height))#写值
 
plt.show()

还可以对数据进行保存:可用excel打开

#保存数据
from pandas import DataFrame
data={'NickName':NickName,'Sex':Sex,'Province':Province,'City':City,'Signature':Signature}
frame=DataFrame(data)
 
frame.to_csv('data.csv',index=True)

以上这篇itchat和matplotlib的结合使用爬取微信信息的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用Python的Supervisor进行进程监控以及自动启动
May 29 Python
python实现简单购物商城
May 21 Python
浅谈Python生成器generator之next和send的运行流程(详解)
May 08 Python
Python编写登陆接口的方法
Jul 10 Python
Python与R语言的简要对比
Nov 14 Python
Python使用sax模块解析XML文件示例
Apr 04 Python
pycharm配置当鼠标悬停时快速提示方法参数
Jul 31 Python
python中hasattr()、getattr()、setattr()函数的使用
Aug 16 Python
Python多线程及其基本使用方法实例分析
Oct 29 Python
Windows系统下pycharm中的pip换源
Feb 23 Python
Python celery原理及运行流程解析
Jun 13 Python
通过Django Admin+HttpRunner1.5.6实现简易接口测试平台
Nov 11 Python
用 Python 爬了爬自己的微信朋友(实例讲解)
Aug 25 #Python
详解python基础之while循环及if判断
Aug 24 #Python
用Python实现随机森林算法的示例
Aug 24 #Python
python利用urllib实现爬取京东网站商品图片的爬虫实例
Aug 24 #Python
python 接口_从协议到抽象基类详解
Aug 24 #Python
Python调用ctypes使用C函数printf的方法
Aug 23 #Python
使用Python实现博客上进行自动翻页
Aug 23 #Python
You might like
ThinkPHP查询返回简单字段数组的方法
2014/08/25 PHP
Ajax中的JSON格式与php传输过程全面解析
2017/11/14 PHP
php 字符串中是否包含指定字符串的多种方法
2018/04/12 PHP
PHP手机短信验证码实现流程详解
2018/05/17 PHP
php输出反斜杠的实例方法
2019/09/19 PHP
laravel框架如何设置公共头和公共尾
2019/10/22 PHP
jQuery学习笔记之jQuery的DOM操作
2010/12/22 Javascript
24款非常有用的 jQuery 插件分享
2011/04/06 Javascript
jQuery EasyUI API 中文文档 DateTimeBox日期时间框
2011/10/16 Javascript
jQuery老黄历完整实现方法
2015/01/16 Javascript
JavaScript数组Array对象增加和删除元素方法总结
2015/01/20 Javascript
ES6扩展运算符的用途实例详解
2017/08/20 Javascript
使用webpack-dev-server处理跨域请求的方法
2018/04/18 Javascript
微信小程序定位当前城市的方法
2018/07/19 Javascript
PHPStorm中如何对nodejs项目进行单元测试详解
2019/02/28 NodeJs
微信小程序 wx:for遍历循环使用实例解析
2019/09/09 Javascript
node.js中事件触发器events的使用方法实例分析
2019/11/23 Javascript
原生JS实现汇率转换功能代码实例
2020/05/13 Javascript
VUE中V-IF条件判断改变元素的样式操作
2020/08/09 Javascript
多个Vue项目部署到服务器的步骤记录
2020/10/22 Javascript
Python中最大最小赋值小技巧(分享)
2017/12/23 Python
用python实现对比两张图片的不同
2018/02/05 Python
python实现画一颗树和一片森林
2018/06/25 Python
python输入多行字符串的方法总结
2019/07/02 Python
python配置文件写入过程详解
2019/10/19 Python
Kathmandu新西兰官网:新西兰户外运动品牌
2019/07/27 全球购物
Gretna Green中文官网:苏格兰格林小镇
2019/10/16 全球购物
华美博弈C/VC工程师笔试试题
2012/07/16 面试题
年度献血先进个人事迹材料
2014/02/14 职场文书
人力管理专业毕业生求职信
2014/02/27 职场文书
机械制造毕业生求职信
2014/03/03 职场文书
村长党的群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
研究生导师推荐信
2015/03/25 职场文书
酒店人事专员岗位职责
2015/04/07 职场文书
虚拟机linux端mysql数据库无法远程访问的解决办法
2021/05/26 MySQL
vscode内网访问服务器的方法
2022/06/28 Servers