Use Python to make a confession artifact-love wall

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only. They do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it yourself

Python free learning materials and group communication answers Click to join


1. Wall of Love ❤️

Collect the avatars of fans through the crawler, and then use the PIL library to splice out the shape of the love wall:

 

Two, code analysis

1. Avatar crawling

Click on my fans in the personal center to see your fans. By capturing the packet, you can see that the corresponding interface is:

url = 'https://me.csdn.net/api/relation/index?pageno=1&pagesize=20&relation_type=fans' # 接口地址

Then, you can define a function to get fan information:

def get_fansInfo():
    '''
    获取粉丝相关信息
    '''
    url = 'https://me.csdn.net/api/relation/index?pageno=%d&pagesize=%d&relation_type=fans' # 接口地址
    cookies = {} # 用户登陆cookies
    headers = {  # 请求头
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Referer': 'https://i.csdn.net/',
        'Origin': 'https://i.csdn.net',
        'Connection': 'keep-alive',
        'TE': 'Trailers',
    }
    # 获取粉丝总数
    res = requests.get(url%(1,10),headers=headers,cookies=cookies)
    res_json = res.json()
    N_fans = res_json['data']['data_all']
    print('一共有%d个粉丝'%N_fans)
    # 获取全部粉丝数据
    res = requests.get(url%(1,N_fans),headers=headers,cookies=cookies)
    res_json = res.json()
    return res_json

The returned data includes an avatar field, which is the user's avatar address. After getting the avatar address, you can define a function to download the corresponding avatar:

def download_avatar(username,url):
    '''
    下载用户头像
    '''
    savePath = './avatars' # 头像存储目录
    res = requests.get(url)
    with open('%s/%s.jpg'%(savePath,username),'wb') as f:
        f.write(res.content)

Define the main function and run the code:

if __name__ == '__main__':
    fans = get_fansInfo()
    for f in fans['data']['list']:
        username = f['fans'] # 用户名
        url = f['avatar']    # 头像地址
        download_avatar(username,url)
        print('用户"%s"头像下载完成!'%username)

Finally, I successfully downloaded all the avatars to the local folder:

 

2. Head portrait

Smart, you should have discovered that there are two avatars repeated in the crawled avatars (presumably this should be the official default avatar):

 

 

Therefore, in order to better display, we have to de-duplicate the avatar. Here we use the MD5 value of each avatar to perform deduplication. First, define a function to calculate the MD5 value of the avatar:

def get_md5(filename):
    '''
    获取文件的md5值cls
    '''
    m = hashlib.md5()
    with open(filename,'rb') as f:
        for line in f:
            m.update(line)
    md5 = m.hexdigest()
    return md5

Note: The summary is calculated for each file through MD5. In theory, the MD5 value will be the same only if the files are completely consistent. Therefore, it can be used for image deduplication.
De-duplicate the avatar, and save the de-duplicated avatar in another directory:

# 照片去重
md5_already = [] # 用于存储已经记录过的图片,便于去重
for filename in os.listdir('./avatars'):
    md5 = get_md5('./avatars/'+filename)  
    if md5 not in md5_already:
        md5_already.append(md5)
        shutil.copyfile('./avatars/'+filename,'./avatars(dr)/'+filename)

3. Draw a love wall

This step mainly uses the PIL library in python to stitch the avatar into a larger picture according to the set frame. First import the relevant library:

import os
import random
import numpy as np
import PIL.Image as Image

Define the frame for drawing graphics (represented by a two-dimensional array):

FRAME = [[0,1,1,0,0,0,0,1,1,0],
         [1,1,1,1,0,0,1,1,1,1],
         [1,1,1,1,1,1,1,1,1,1],
         [1,1,1,1,1,1,1,1,1,1],
         [0,1,1,1,1,1,1,1,1,0],
         [0,0,1,1,1,1,1,1,0,0],
         [0,0,0,1,1,1,1,0,0,0],
         [0,0,0,0,1,1,0,0,0,0]]

Here everyone can use their imagination and draw what you think

Among them, 0 means not to fill in, 1 means to fill in with avatar.

Define the relevant parameters, including the size of each avatar used for filling, the number of times each point is filled, etc.:

# 定义相关参数
SIZE = 50 # 每张图片的尺寸为50*50
N = 2     # 每个点位上放置2*2张图片

# 计算相关参数
width = np.shape(FRAME)[1]*N*SIZE  # 照片墙宽度
height = np.shape(FRAME)[0]*N*SIZE # 照片墙高度
n_img = np.sum(FRAME)*(N**2)       # 照片墙需要的照片数
filenames = random.sample(os.listdir('./avatars(dr)'),n_img) # 随机选取n_img张照片
filenames = ['./avatars(dr)/'+f for f in filenames]

Traverse FRAME and fill the background image with the avatar:

# 绘制爱心墙
img_bg = Image.new('RGB',(width,height)) # 设置照片墙背景
i = 0
for y in range(np.shape(FRAME)[0]):
    for x in range(np.shape(FRAME)[1]):
         if FRAME[y][x] == 1: # 如果需要填充
             pos_x = x*N*SIZE # 填充起始X坐标位置
             pos_y = y*N*SIZE # 填充起始Y坐标位置
             for yy in range(N):
                 for xx in range(N):
                     img = Image.open(filenames[i])
                     img = img.resize((SIZE,SIZE),Image.ANTIALIAS)
                     img_bg.paste(img,(pos_x+xx*SIZE,pos_y+yy*SIZE))
                     i += 1
                
# 保存图片
img_bg.save('love.jpg')

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/112819554