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

yipeiwu_com7年前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开发中爬虫使用代理proxy抓取网页的方法示例

本文实例讲述了Python开发中爬虫使用代理proxy抓取网页的方法。分享给大家供大家参考,具体如下: 代理类型(proxy):透明代理 匿名代理 混淆代理和高匿代理. 这里写一些pyt...

总结python爬虫抓站的实用技巧

总结python爬虫抓站的实用技巧

前言 写过的这些脚本有一个共性,都是和web相关的,总要用到获取链接的一些方法,累积不少爬虫抓站的经验,在此总结一下,那么以后做东西也就不用重复劳动了。 1.最基本的抓站 impor...

Python网络爬虫之爬取微博热搜

Python网络爬虫之爬取微博热搜

微博热搜的爬取较为简单,我只是用了lxml和requests两个库 url= https://s.weibo.com/top/summary?Refer=top_hot&topnav=1...

玩转python爬虫之cookie使用方法

玩转python爬虫之cookie使用方法

之前一篇文章我们学习了爬虫的异常处理问题,那么接下来我们一起来看一下Cookie的使用。 为什么要使用Cookie呢? Cookie,指某些网站为了辨别用户身份、进行session跟踪而...

选择Python写网络爬虫的优势和理由

选择Python写网络爬虫的优势和理由

什么是网络爬虫? 网络爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。传统爬虫从一个或若干初始网页的URL开始,获得初始网页上的URL,在抓取网页的过...