python 玩微信,超有趣

itchat

無意間發現的一個有意思的開源項目itchat,相當於微信api,掃碼登錄後去抓包爬取信息,還可以post去發送信息。 GitHub star數量4,非常火,作者是@LittleCoder,已經把微信的接口完成了,大大的方便了我們對微信的挖掘,以下的功能也通過itchat來實現。

安裝itchat這個庫

pip install itchat

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

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

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

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 玩微信,超有趣

結果是個意外。。。。 ##2. 好友暱稱,備註,以及個性簽名 其實還可以爬出很多每個好友的其他屬性,比如家鄉等等信息! 直接上代碼:

# coding:utf-8
import itchat
# 先登錄
itchat.login()
# 獲取好友列表
friends = itchat.get_friends(update=True)[0:]
for i in friends:
# 獲取個性簽名
# print(i)
name = i['RemarkName']
nickname = i['NickName']
# 正則匹配過濾掉emoji表情,例如emoji1f3c3等
signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji",
"")
print(name + "," + nickname + "," + signature)

運行效果如圖:

python 玩微信,超有趣

##3.好友個性簽名詞雲 獲取好友列表的時候,返回的json信息中還看到了有個性簽名的信息,腦洞一開,把大家的個性簽名都抓下來,看看高頻詞語,還做了個詞雲。 先全部抓取下來 打印之後你會發現,有大量的span,class,emoji,emoji1f3c3等的字段,因為個性簽名中使用了表情符號,這些字段都是要過濾掉的,寫個正則和replace方法過濾掉 貼代碼:

# wordcloud詞雲
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import os
import numpy as np
import PIL.Image as Imaged
import itchat
os.path.dirname(__file__)
alice_coloring = np.array(Imaged.open(os.path.join('/Users/t-mac/desktop', "640.jpeg")))
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('/Users/t-mac/desktop', "wechat_cloud.png"))
itchat.send_image("wechat_cloud.png", 'filehelper')

效果如圖:

python 玩微信,超有趣


分享到:


相關文章: