Python二次元壁纸爬虫:获取高分辨率电脑壁纸
以下是一个简单的Python爬虫程序,可以爬取二次元电脑壁纸并保存符合要求的壁纸(分辨率高于1920x1080)。
import requests
from bs4 import BeautifulSoup
from PIL import Image
import io
# 爬取的页面地址
url = 'https://www.wallpapermaiden.com/category/anime'
# 请求页面内容
response = requests.get(url)
# 解析页面内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取所有壁纸元素
wallpapers = soup.find_all('div', class_='thumb')
# 遍历壁纸元素并下载符合规格的壁纸
for wallpaper in wallpapers:
# 获取壁纸的尺寸信息
size_info = wallpaper.find('div', class_='info').text.strip()
width, height = size_info.split('x')
width = int(width)
height = int(height)
# 判断壁纸是否符合要求,不符合则跳过
if width < 1920 or height < 1080:
continue
# 获取壁纸的下载链接
download_link = wallpaper.find('a')['href']
# 请求壁纸的二进制数据
wallpaper_data = requests.get(download_link).content
# 将二进制数据转换为Image对象
wallpaper_image = Image.open(io.BytesIO(wallpaper_data))
# 保存壁纸到本地文件夹
wallpaper_image.save(f'{width}x{height}.jpg')
说明:
- 首先定义了要爬取的页面地址,然后使用requests库发送请求并获取页面内容。
- 使用BeautifulSoup库解析页面内容,并获取所有壁纸元素。
- 遍历壁纸元素,获取每个壁纸的尺寸信息和下载链接。
- 判断每个壁纸是否符合要求,如果不符合则跳过。
- 请求壁纸的二进制数据,并使用PIL库将二进制数据转换为Image对象。
- 将Image对象保存到本地文件夹中,文件名为壁纸的尺寸信息。
原文地址: https://www.cveoy.top/t/topic/nhug 著作权归作者所有。请勿转载和采集!