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()
相关推荐
likuolei16 分钟前
XML 元素 vs. 属性
xml·java·开发语言
X***489620 分钟前
C源代码生成器
c语言·开发语言
梁正雄26 分钟前
2、Python流程控制
开发语言·python
catchadmin1 小时前
PHP True Async RFC 被拒——原生异步离 PHP 还有多远?
开发语言·php
J***79391 小时前
PHP在电商中的Magento
开发语言·php
python零基础入门小白1 小时前
【万字长文】大模型应用开发:意图路由与查询重写设计模式(从入门到精通)
java·开发语言·设计模式·语言模型·架构·大模型应用开发·大模型学习
Eric.Lee20212 小时前
ubuntu 安装 Miniconda
linux·运维·python·ubuntu·miniconda
天若有情6732 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
无心水2 小时前
【Python实战进阶】1、Python高手养成指南:四阶段突破法从入门到架构师
开发语言·python·django·matplotlib·gil·python实战进阶·python工程化实战进阶
李剑一2 小时前
Python学习笔记1
python