用Python写一个爬取二次元电脑壁纸的爬虫并保存壁纸等于或高于1920x1080的低于1920x1080的不要
以下是一个简单的二次元电脑壁纸爬虫,使用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'}
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的壁纸。每个壁纸将被保存到当前工作目录中,并命名为其原始文件名。
原文地址: http://www.cveoy.top/t/topic/bTdM 著作权归作者所有。请勿转载和采集!