前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Python】利用python爬取微信朋友info

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

作者头像
肓己
发布2021-08-12 10:26:07
6601
发布2021-08-12 10:26:07
举报
文章被收录于专栏:linux commands

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

#安装itchat

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

#统计微信好友男女比例

代码语言:javascript
复制
#-*- 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' )

#抓取好友头像并拼成图

代码语言:javascript
复制
# -*- 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')

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

代码语言:javascript
复制
#获取好友签名信息
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"))

#制作聊天机器人

代码语言:javascript
复制
#-*- 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/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/09/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云图数据可视化
腾讯云图数据可视化(Tencent Cloud Visualization) 是一站式数据可视化展示平台,旨在帮助用户快速通过可视化图表展示大量数据,低门槛快速打造出专业大屏数据展示。精心预设多种行业模板,极致展示数据魅力。采用拖拽式自由布局,全图形化编辑,快速可视化制作。腾讯云图数据可视化支持多种数据来源配置,支持数据实时同步更新,同时基于 Web 页面渲染,可灵活投屏多种屏幕终端。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档