以下是一个简单的 Python 爬虫程序,可以从指定的网站上爬取二次元电脑壁纸并保存符合要求的壁纸。

import requests
from bs4 import BeautifulSoup
import os

# 需要爬取的网站URL
url = 'https://wall.alphacoders.com/by_sub_category.php?id=173010&name=Anime+Wallpapers&lang=Chinese'

# 请求网站HTML内容
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# 创建目录
if not os.path.exists('anime_wallpapers'):
    os.mkdir('anime_wallpapers')

# 爬取所有图片链接并下载符合要求的图片
for link in soup.find_all('a'):
    href = link.get('href')
    if href and href.startswith('/big.php?i='):
        image_url = 'https://wall.alphacoders.com' + href
        response = requests.get(image_url)
        image_name = href.split('=')[-1] + '.jpg'
        image_path = os.path.join('anime_wallpapers', image_name)
        with open(image_path, 'wb') as f:
            f.write(response.content)
            f.close()
        # 检查图片是否符合要求
        os.system(f'sips -g pixelHeight -g pixelWidth {image_path}')
        result = os.popen(f'sips -g pixelHeight -g pixelWidth {image_path}').read()
        width = int(result.split('
')[1].split(': ')[-1])
        height = int(result.split('
')[2].split(': ')[-1])
        if width >= 1920 and height >= 1080:
            print(f'{image_name} saved.')
        else:
            os.remove(image_path)
            print(f'{image_name} deleted.')

程序的流程如下:

  1. 首先定义需要爬取的网站URL。
  2. 使用requests库请求网站HTML内容,并使用BeautifulSoup库解析HTML。
  3. 创建一个目录用于保存所有符合要求的壁纸。
  4. 遍历HTML中所有的链接,找到图片链接并下载到本地。
  5. 对于每一张图片,使用命令行工具sips获取图片的宽度和高度。
  6. 如果图片的宽度和高度都大于等于1920x1080,则将其保留,否则将其删除。

需要注意的是,这个程序中使用了sips命令行工具来获取图片的宽度和高度,因此只能在macOS系统上运行。如果你使用的是其他操作系统,可以使用Pillow库来获取图片的宽度和高度。

Python 爬虫:获取二次元电脑壁纸并筛选 1920x1080 及以上分辨率

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

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