#扫描二维码登录
import itchat
itchat.auto_login()
#读取好友信息 0是自己
friends = itchat.get_friends(update=True)[1:]
#初始化字典
df_col = []
wechat_dic = dict()
for key in friends[0]:
df_col.append(key)
wechat_dic[key]=[]
#信息存入字典
for ele in friends:
try:
for key in df_col:
wechat_dic[key].append(ele[key])
except KeyError:
print(ele)
break
#字典转换成DataFrame
import pandas as pd
wechat_df = pd.DataFrame(wechat_dic)
#爬取好友头像信息
#失败的方法1 利用wechat_df中的url (url不明原因,不能请求)
#该url不能直接用,需要前面拼接http://wx.qq.com
wechat_df['HeadImgUrl'] = wechat_df[['HeadImgUrl']].apply(lambda x:'http://wx.qq.com'+x['HeadImgUrl'],axis = 1)
import os
import requests
folder_path = './photo/wechat'
if os.path.exists(folder_path) == False: # 判断文件夹是否已经存在
os.makedirs(folder_path)
for index,row in wechat_df.iterrows():
try:
html = requests.get(row['HeadImgUrl'])
img_name = row['NickName']+'.png'
with open(folder_path+img_name, 'wb') as file: # 以byte形式将图片数据写入
file.write(html.content)
file.flush()
file.close()
time.sleep(0.1)
except BaseException:
print(row['NickName'],'没有头像')
#爬取好友信息
#方法二 用好友的微信昵称命名图片 昵称有特殊字符就用备注名字命名
for ele in friends:
img = itchat.get_head_img(ele["UserName"])
try:
with open('./photo/wechat/' + ele['NickName'] + ".jpg",'wb') as f:
f.write(img)
f.close()
except OSError:
with open('./photo/wechat/' + 'SSB' + ele['RemarkName']+".jpg",'wb') as f:
f.write(img)
f.close()
#头像拼接
#参考 https://cloud.tencent.com/developer/article/1111559
import PIL.Image as Image
import math
import os
import random
image_name = os.listdir('./photo/wechat')
#20*21
length = len(image_name)#len为412,坏2张 一共410张图片
lines = 20
image = Image.new('RGBA', (400, 420),'white')
x = 0
y = 0
image_name =image_name+ random.sample(image_name, 10) #随机生成10 凑够420张
for ele in image_name:
try:
img = Image.open('./photo/wechat/' + ele)
img = img.resize((20, 20), Image.ANTIALIAS) #resize image with high-quality
image.paste(img, (x * 20, y * 20))
x += 1
if x == lines:
x = 0
y += 1
except BaseException:
print(ele+'无法打开')
image.convert('RGB').save('./photo/' + "all.jpg")
image.show()
python itchat爬取微信好友信息
猜你喜欢
转载自blog.csdn.net/wangzhanxidian/article/details/83451401
今日推荐
周排行