Python网络爬虫获取Wallhaven壁纸图片(源码)

**

话不多说,直接附源码,可运行!

**

python 复制代码
import requests
from lxml import etree
from fake_useragent import UserAgent
import time


class wallhaven(object):
    def __init__(self):
        # yellow
        # self.url = "https://wallhaven.cc/search?colors=cc6633&page={}"
        # girl
        self.url = "https://wallhaven.cc/search?q=girl&categories=111&purity=110&sorting=date_added&order=desc&ai_art_filter=0&page={}"
        ua = UserAgent()
        for i in range(1, 50):
            self.headers = {
                'User-Agent': ua.random,
            }

    def get_page(self, url):
        res = requests.get(url=url, headers=self.headers)
        html = res.content.decode("utf-8")
        return html

    def parse_page(self, html):
        parse_html = etree.HTML(html)
        image_src_list = parse_html.xpath('//figure//a/@href')
        print("当前图片Url列表:", image_src_list)

        for image_src in image_src_list:
            html1 = self.get_page(image_src)  # 二级页面发生请求
            parse_html1 = etree.HTML(html1)
            filename = parse_html1.xpath('//div[@class="scrollbox"]//img/@src')
            if filename is None:
                continue
            for img in filename:
                dirname = "./images/other/" + img[32:]
                html2 = requests.get(url=img, headers=self.headers).content
                with open(dirname, 'wb') as f:
                    f.write(html2)
                    print(f"图片{filename}下载成功:")

    def main(self):
        startPage = 12
        endPage = 99
        for page in range(startPage, endPage + 1):
            print("获取当前页面图片,页码:", page)
            url = self.url.format(page)
            html = self.get_page(url)
            self.parse_page(html)
            time.sleep(1.4)


if __name__ == '__main__':
    imageSpider = wallhaven()
    imageSpider.main()
相关推荐
uppp»37 分钟前
深入理解 Java 反射机制:获取类信息与动态操作
java·开发语言
Yan-英杰38 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779132 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥3 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
小喵要摸鱼7 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover17 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt