以下是一个简单的二次元电脑壁纸爬虫,使用 Python 的 requests 和 BeautifulSoup 库来获取和解析网页,并使用 urllib 库来下载图片。

import requests
from bs4 import BeautifulSoup
import urllib.request

url = 'https://wallhaven.cc/search?q=anime&categories=110&purity=100&sorting=random&order=desc&page='  # 网站链接
page_num = 1
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}  # 设置 User-Agent

while True:
    # 获取网页内容
    response = requests.get(url + str(page_num), headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    
    # 查找所有的图片标签
    images = soup.find_all('img', class_='lazyload')
    
    # 遍历每个图片标签
    for img in images:
        # 获取图片链接和分辨率
        img_url = img['data-src']
        resolution = img['data-wallpaper-width'] + 'x' + img['data-wallpaper-height']
        
        # 下载分辨率等于或高于 1920x1080 的图片
        if int(img['data-wallpaper-width']) >= 1920 and int(img['data-wallpaper-height']) >= 1080:
            # 获取文件名并下载图片
            file_name = img_url.split('/')[-1]
            urllib.request.urlretrieve(img_url, file_name)
            print('Downloaded', file_name, 'with resolution', resolution)
    
    # 如果没有更多的页面,退出
    if soup.find('a', class_='thumb-info-wrapper') is None:
        break
    
    # 增加页面计数器
    page_num += 1

这个爬虫会从 wallhaven.cc 网站中搜索 'anime' 类别、纯净度为 100%、随机排序的壁纸,并遍历每一页,下载所有分辨率等于或高于 1920x1080 的壁纸。每个壁纸将被保存到当前工作目录中,并命名为其原始文件名。

注意:

  • 为了避免网站反爬,建议使用代理 IP 或设置合理的请求频率,避免频繁访问导致封禁。
  • 爬取网站内容前请务必遵守网站的使用条款和 robots.txt 协议,尊重网站的版权。

更多信息:

  • requests 库:https://requests.readthedocs.io/
  • BeautifulSoup 库:https://beautiful-soup-4.readthedocs.io/
  • urllib 库:https://docs.python.org/3/library/urllib.html
Python 爬虫抓取二次元电脑壁纸:超清壁纸下载教程

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

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