代碼放在這里:wzyonggege/python-wechat-itchat

詞雲那里可以換成小黃人圖片

---------------------------------------------------------------------------------------------------

0. itchat

最近研究了一些微信的玩法,我們可以通過網頁版的微信微信網頁版,掃碼登錄后去抓包爬取信息,還可以post去發送信息。

然后發現了itchat這個開源項目,作者是@LittleCoder,已經把微信的接口完成了,大大的方便了我們對微信的挖掘,以下的功能也通過itchat來實現。

安裝itchat這個庫

pip install itchat

先來段簡單的試用,實現微信的登錄,運行下面代碼會生成一個二維碼,掃碼之后手機端確認登錄,就會發送一條信息給‘filehelper’,這個filehelper就是微信上的文件傳輸助手。

import itchat # 登錄 itchat.login() # 發送消息 itchat.send(u'你好', 'filehelper') 

除了登錄和發送消息我們還可以這么來玩,往下走~

1. 微信好友男女比例

想統計下自己微信里好友的性別比例,當然也是很簡單,先獲取好友列表,統計列表里性別計數

import itchat # 先登錄 itchat.login() # 獲取好友列表 friends = itchat.get_friends(update=True)[0:] # 初始化計數器,有男有女,當然,有些人是不填的 male = female = other = 0 # 遍歷這個列表,列表里第一位是自己,所以從"自己"之后開始計算 # 1表示男性,2女性 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:]) # 好了,打印結果 print u"男性好友:%.2f%%" % (float(male) / total * 100) print u"女性好友:%.2f%%" % (float(female) / total * 100) print u"其他:%.2f%%" % (float(other) / total * 100) 

好看看結果:

(好吧,暴露了我男性友人較多的真相~~)

好像不夠直觀,有興趣的朋友可以加上可視化的展示,我這里用基於python的Echarts(有機會再細講) 
先安裝了

pip install echarts-python

展示比例一般使用百分比圓餅表吧

# 使用echarts,加上這段 from echarts import Echart, Legend, Pie chart = Echart(u'%s的微信好友性別比例' % (friends[0]['NickName']), 'from WeChat') chart.use(Pie('WeChat', [{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)}, {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)}, {'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}], radius=["50%", "70%"])) chart.use(Legend(["male", "female", "other"])) del chart.json["xAxis"] del chart.json["yAxis"] chart.plot() 

登登登登~

2. 好友個性簽名詞雲

獲取好友列表的時候,返回的json信息中還看到了有個性簽名的信息,腦洞一開,把大家的個性簽名都抓下來,看看高頻詞語,還做了個詞雲。

# coding:utf-8 import itchat # 先登錄 itchat.login() # 獲取好友列表 friends = itchat.get_friends(update=True)[0:] for i in friends: # 獲取個性簽名 signature = i["Signature"] print signature 

先全部抓取下來 
打印之后你會發現,有大量的span,class,emoji,emoji1f3c3等的字段,因為個性簽名中使用了表情符號,這些字段都是要過濾掉的,寫個正則和replace方法過濾掉

for i in friends: # 獲取個性簽名 signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "") # 正則匹配過濾掉emoji表情,例如emoji1f3c3等 rep = re.compile("1f\d.+") signature = rep.sub("", signature) print signature 

接來下用jieba分詞,然后制作成詞雲,首先要安裝jieba和wordcloud庫

pip install jieba
pip install wordcloud

代碼

# coding:utf-8 import itchat import re itchat.login() friends = itchat.get_friends(update=True)[0:] tList = [] for i in friends: signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "") rep = re.compile("1f\d.+") signature = rep.sub("", signature) tList.append(signature) # 拼接字符串 text = "".join(tList) # jieba分詞 import jieba wordlist_jieba = jieba.cut(text, cut_all=True) wl_space_split = " ".join(wordlist_jieba) # wordcloud詞雲 import matplotlib.pyplot as plt from wordcloud import WordCloud import PIL.Image as Image # 這里要選擇字體存放路徑,這里是Mac的,win的字體在windows/Fonts中 my_wordcloud = WordCloud(background_color="white", max_words=2000, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf').generate(wl_space_split) plt.imshow(my_wordcloud) plt.axis("off") plt.show() 

運行代碼

這。。好像有點丑,根據wordcloud用法,我可以找一張圖來生成配色方案,我這里找了一張微信的logo

修改一下代碼

# wordcloud詞雲 import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator import os import numpy as np import PIL.Image as Image d = os.path.dirname(__file__) alice_coloring = np.array(Image.open(os.path.join(d, "wechat.jpg"))) my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf')\ .generate(wl_space_split) image_colors = ImageColorGenerator(alice_coloring) plt.imshow(my_wordcloud.recolor(color_func=image_colors)) plt.imshow(my_wordcloud) plt.axis("off") plt.show() # 保存圖片 並發送到手機 my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png")) itchat.send_image("wechat_cloud.png", 'filehelper') 

 

嗯~好像還可以,這是Mac下生成的,附一個win10下生成的

3. 微信自動回復

接着來實現一個類似qq上的自動回復,原理就是接收到消息,就發消息回去,同時發一條給文件助手,就可以在文件助手中統一查看消息。

代碼很簡單,來看看

#coding=utf8 import itchat # 自動回復 # 封裝好的裝飾器,當接收到的消息是Text,即文字消息 @itchat.msg_register('Text') def text_reply(msg): # 當消息不是由自己發出的時候 if not msg['FromUserName'] == myUserName: # 發送一條提示給文件助手 itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])), msg['User']['NickName'], msg['Text']), 'filehelper') # 回復給好友 return u'[自動回復]您好,我現在有事不在,一會再和您聯系。\n已經收到您的的信息:%s\n' % (msg['Text']) if __name__ == '__main__': itchat.auto_login() # 獲取自己的UserName myUserName = itchat.get_friends(update=True)[0]["UserName"] itchat.run() 

運行后會保持登錄狀態,開啟自動回復模式,手機上查看:

當然,除了文字Text信息,還可以接收圖片(表情包算圖片),語音,名片,地理位置,分享和類型為Note的信息(就是有人提示類的消息,例如撤回消息),把裝飾器寫成下面形式即可接受,大家可以試試

@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])



學習過程中遇到什么問題或者想獲取學習資源的話,歡迎加入學習交流群
626062078,我們一起學Python!