Confession artifact! Teach you how to use Python to draw a wall of love to get your heart!

1. Wall of Love

Collect the avatars of fans through crawlers, and then use the PIL library to splice out the shape of the love wall
Insert picture description here

Two, code analysis

1. Avatar crawling

Click on my fans in the personal center to see your fans

Through packet capture, 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:

Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
For these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code!
QQ group:810735403

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:
Insert picture description here
2. Deduplication of avatars

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

Insert picture description here
Ever since, in order to better display, we have to de-duplicate the avatar

Here we use the MD5 value of each avatar to perform deduplication, and then 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 : Each file uses MD5 to calculate the summary. In theory, the MD5 value will be the same only if the files are completely consistent. Therefore, it can be used to de-duplicate images

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 the love wall
This step is mainly to use the PIL library 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 no filling, and 1 means filling with a profile picture.

Define related 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')

Write at the end

The weather is getting colder, I hope this little confession can bring you some warmth; I hope the wind and rain will not forget the way back; I hope that the body can be like a moon pavilion and travel with the king for thousands of miles!

Here I still want to recommend the Python development exchange learning (qq) group I built:, the 810735403group is all learning Python development, if you are learning Python, you are welcome to join, everyone is a software development party, sharing dry goods from time to time (Only related to Python software development), including a copy of the latest Python advanced materials and advanced development tutorials compiled by myself in 2020, welcome to advanced and those who want to go deep into Python!

Guess you like

Origin blog.csdn.net/XIe_0928/article/details/112469091
Recommended