itchat 儲存好友資訊以及生成好友頭像圖片牆
2019 第 41 篇,總第 65 篇文章
本文大約 4000 字,閱讀大約需要 12 分鐘
最近簡單運用 itchat 這個庫來實現一些簡單的應用,主要包括以下幾個應用:
-
統計儲存好友的數量和資訊
-
統計和儲存關注的公眾號數量和資訊
-
簡單生成好友頭像的圖片牆,利用一個第三方庫生成馬賽克風格的圖片牆
itchat 的 github 專案地址如下,這是一個開源的微信個人介面:
https://github.com/littlecodersh/ItChat
這個庫的安裝也很簡單,直接用 pip install itchat
即可安裝
接下來就開始介紹如何利用這個庫來實現上述操作。
1. 統計儲存好友的數量和資訊
首先是微信登入,簡單的幾行程式碼即可實現:
import itchat
# 避免頻繁掃描二維碼登入
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
執行這段程式碼後,就會彈出一個二維碼,進行掃描登入,其中 hotReload=True
是保證不用每次執行程式都需要彈出二維碼掃描登入。
然後是獲取好友的資訊:
we_friend = itchat.get_friends(update=True)[:]
這裡 we_friend
就是儲存了好友資訊的一個字典,並且 we_friend[0]
是儲存使用者自己的資訊,從 we_friend[1]
開始才是真正的好友的資訊,這裡我們將主要儲存以下資訊:
key | 含義 |
---|---|
NickName | 暱稱 |
RemarkName | 備註 |
Sex | 性別 |
Province | 省份 |
City | 城市 |
Signature | 簽名 |
儲存好友的資訊程式碼如下:
friends = we_friend[1:]
total_numbers = len(friends)
print('你的好友數量為: {}'.format(total_numbers))
friend_infos_dict = {}
for fri_info in friends:
for key in friend_key:
if friend_infos_dict.get(key, False):
friend_infos_dict[key].append(fri_info[key])
else:
friend_infos_dict[key] = [fri_info[key]]
# 儲存資訊
fri_save_file_name = os.path.join(save_file_path, '好友資訊.csv')
df = pd.DataFrame(friend_infos_dict)
df.to_csv(fri_save_file_name, sep=',')
其中 save_file_path
是指定儲存好友資訊檔案的資料夾路徑,
2. 儲存公眾號資訊
獲取公眾號資訊並儲存的程式碼如下:
# 公眾號獲取的資訊內容,分別是暱稱、城市、城市、簽名
mps_key = ['NickName', 'City', 'Province', 'Signature']
# 獲取公眾號資訊
mps = itchat.get_mps(update=True)
mps_num = len(mps)
print('你關注的公眾號數量: {}'.format(mps_num))
mps_save_file_name = os.path.join(save_file_path, '公眾號資訊.csv')
mps_dict = {}
for mp in mps:
for key in mps_key:
if mps_dict.get(key, False):
mps_dict[key].append(mp[key])
else:
mps_dict[key] = [mp[key]]
df = pd.DataFrame(mps_dict)
df.to_csv(mps_save_file_name, sep=',', encoding='utf-8')
3. 生成好友頭像圖片牆
首先同樣需要獲取好友的頭像,並儲存到本地,程式碼如下:
def save_head_photo(save_photo_dir):
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
friends = itchat.get_friends(update=True)[1:]
# 採集好友頭像並儲存到本地
num = 0
for fri in friends:
img = itchat.get_head_img(userName=fri['UserName'])
img_path = os.path.join(save_photo_dir, str(num) + '.jpg')
if not os.path.exists(img_path):
file_image = open(img_path, 'wb')
file_image.write(img)
file_image.close()
num += 1
print('完成好友頭像儲存至路徑: ', save_photo_dir)
其中獲取頭像的函式是 itchat.get_head_image()
。
接著就是生成好友頭像的圖片牆,這裡有兩種方式,第一種是比較常規的生成方法。首先需要匯入以下庫
import itchat
import math
import PIL.Image as Image
import os
接著是設定畫布大小及每行的頭像數量,頭像的大小,程式碼是:
# 畫布大小
image_size = 1280
# 算出每張圖片的大小多少合適
each_size = int(math.sqrt(float(image_size * image_size) / len(ls)))
# 每行圖片數量
lines = int(image_size / each_size)
print('each_size={}, lines={}'.format(each_size, lines))
# 建立 1280*1280 的畫布
image = Image.new('RGBA', (image_size, image_size))
利用的是 pillow
庫,安裝方式是 pip install pillow
。這裡我設定的畫布大小就是 1280 * 1280。
然後就是讀取儲存的頭像,並逐一貼上到畫布上,程式碼如下:
# 讀取儲存的好友頭像圖片
ls = os.listdir(save_photo_dir)
for i in range(0, len(ls)):
try:
img_path = os.path.join(save_photo_dir, str(i) + ".jpg")
img = Image.open(img_path)
except IOError:
print("Error for image: {}".format(img_path))
else:
img = img.resize((each_size, each_size), Image.ANTIALIAS)
image.paste(img, (x * each_size, y * each_size))# 貼上位置
x += 1
if x == lines:# 換行
x = 0
y += 1
image.save(os.path.join(os.getcwd(), "好友頭像拼接圖.jpg"))
第二種是參考了 當 Python 遇上你的微信好友 介紹的第三方庫 photomosaic
,安裝方法也很簡單:
pip install photomosaic
這個第三方庫可以生成蒙太奇馬賽克風格的圖片或者視訊。
實現程式碼如下:
import photomosaic as pm
def create_photomosaic(save_photo_dir, background_photo):
# 讀取背景圖片
bg_photo = pm.imread(background_photo)
# 讀取好友頭像圖片,定義圖片庫
pool = pm.make_pool(os.path.join(save_photo_dir, '*.jpg'))
# 製作 50*50 的拼圖馬賽克
image = pm.basic_mosaic(bg_photo, pool, (50, 50))
# 儲存結果
pm.imsave('馬賽克好友頭像圖片.jpg', image)
其中上述的四行程式碼也是最基本的使用程式碼,包括:
-
選擇背景圖片
-
定義圖片庫
-
製作馬賽克拼圖
-
儲存圖片
這裡我簡單選擇了下面這張背景圖片:
生成結果如下:

小結
簡單運用 itchat 實現了以上三個小應用,實際上還可以有更多的應用,比如再根據好友資訊分析性別比例、好友區域分佈、簽名的情感分析、關注的公眾號類別、給特定的好友傳送資訊,以及製作微信機器人等。
本文的程式碼已經上傳到 github 上:
https://github.com/ccc013/Python_Notes/tree/master/Projects/wechatProjects/itchat
也可以按如下操作獲取程式碼:
1.關注公眾號“ 機器學習與計算機視覺 ”
2.在公眾號後臺回覆“
itchat
",即可獲取程式碼
參考:
歡迎關注我的微信公眾號--機器學習與計算機視覺,或者掃描下方的二維碼,大家一起交流,學習和進步!
往期精彩推薦
機器學習系列
Github專案 & 資源教程推薦