使用python itchat包爬取微信好友头像形成矩形头像集的方法

yipeiwu_com5年前Python爬虫

初学python,我们必须干点有意思的事!从微信下手吧!

头像集样例如下:

python itchat包爬取微信好友头像形成矩形头像集

大家可以发朋友圈开启辨认大赛哈哈~

话不多说,直接上代码,注释我写了比较多,大家应该能看懂

import itchat
import os
import PIL.Image as Image
from os import listdir
import math
import sys

print("请输入查询模式:0-显示所有好友头像,但最终矩形头像集最后一行可能残缺;1-头像集为完整矩形,但好友可能不全,即在0模式下舍弃最后一行")
mode = input()
if mode not in ("0","1"):
  print("请按照正确格式输入!")
  sys.exit(0)


# itchat.auto_login(enableCmdQR=True) # 这种登录时控制台生成登录二维码
itchat.login() # 这种登录是生成二维码图片在本地目录

friends = itchat.get_friends(update=True)[0:]  # 核心:得到frieds列表集,内含很多信息

user = friends[0]["UserName"]

w = open(user+"_friends",'a',encoding='utf-8',errors='ignore') # 将friends列表存下来,看看内容
for i in friends:
  w.write(str(i))

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)  # 得到user目录下的所有文件,即各个好友头像

numPic = len(pics)

print("所有好友头像数:"+ str(numPic))

eachsize = int(math.sqrt(float(640 * 640) / numPic))  # 先圈定每个正方形小头像的边长,如果嫌小可以加大

print("小正方形头像边长:"+ str(eachsize))


numrow = int(640 / eachsize)
print("一行小头像数:"+ str(numrow))

if mode == "0":
  numcol = int(math.ceil(numPic * 1.0 / numrow))  # 向上取整
else:
  numcol = int(numPic / numrow)  # 向下取整
  print("舍弃好友数:"+ str(numPic - numrow * numcol))

toImage = Image.new('RGB', (eachsize*numrow, eachsize*numcol)) # 先生成头像集模板


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 == numrow:
      x = 0
      y += 1


toImage.save(user + ".jpg")

# itchat.send_image(user + ".jpg", 'filehelper')  # 自动向文件助手里面添加图片,不需要可以关闭

运行结果:

python itchat包爬取微信好友头像形成矩形头像集

ok!!!

以上这篇使用python itchat包爬取微信好友头像形成矩形头像集的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python代理抓取并验证使用多线程实现

没有使用队列,也没有线程池还在学习只是多线程 复制代码 代码如下: #coding:utf8 import urllib2,sys,re import threading,os impo...

用python3 urllib破解有道翻译反爬虫机制详解

用python3 urllib破解有道翻译反爬虫机制详解

前言 最近在学习python 爬虫方面的知识,网上有一博客专栏专门写爬虫方面的,看到用urllib请求有道翻译接口获取翻译结果。发现接口变化很大,用md5加了密,于是自己开始破解。加上...

python爬虫使用cookie登录详解

python爬虫使用cookie登录详解

前言: 什么是cookie? Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。 比如说有些网站需要登录后才能访问某个...

python 爬取马蜂窝景点翻页文字评论的实现

python 爬取马蜂窝景点翻页文字评论的实现

使用Chrome、python3.7、requests库和VSCode进行爬取马蜂窝黄鹤楼的文字评论(http://www.mafengwo.cn/poi/5426285.html)。...

Python网络爬虫实例讲解

Python网络爬虫实例讲解

聊一聊Python与网络爬虫。 1、爬虫的定义 爬虫:自动抓取互联网数据的程序。 2、爬虫的主要框架 爬虫程序的主要框架如上图所示,爬虫调度端通过URL管理器获取待爬取的URL链接,若...