以下是使用 Python 3 编写的爬取二次元电脑壁纸的爬虫,并将其保存到本地。只会爬取等于或高于 1920x1080 的壁纸。

import requests
from bs4 import BeautifulSoup
import os

# 创建一个文件夹用于保存壁纸
if not os.path.exists('wallpapers'):
    os.mkdir('wallpapers')

# 爬取的网站
url = 'https://wallhaven.cc/search?q=Anime+1920x1080&sorting=random&order=desc&page='

# 爬取10页数据
for i in range(1, 11):
    # 发送请求
    res = requests.get(url + str(i))
    # 解析HTML文档
    soup = BeautifulSoup(res.text, 'html.parser')
    # 找到所有的壁纸链接
    links = soup.select('#thumbs > section > ul > li > figure > a')
    # 遍历链接
    for link in links:
        # 获取壁纸链接
        href = link.get('href')
        # 发送请求
        res = requests.get(href)
        # 解析HTML文档
        soup = BeautifulSoup(res.text, 'html.parser')
        # 找到壁纸
        img = soup.select('#wallpaper')
        # 如果没有找到壁纸,则跳过
        if not img:
            continue
        # 获取壁纸链接
        src = img[0].get('src')
        # 获取壁纸分辨率
        width = int(img[0].get('data-wallpaper-width'))
        height = int(img[0].get('data-wallpaper-height'))
        # 如果分辨率低于1920x1080,则跳过
        if width < 1920 or height < 1080:
            continue
        # 发送请求
        res = requests.get(src)
        # 保存壁纸
        with open('wallpapers/' + src.split('/')[-1], 'wb') as f:
            f.write(res.content)

原文地址: https://www.cveoy.top/t/topic/nhui 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录