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()
相关推荐
耶啵奶膘14 分钟前
uni-app头像叠加显示
开发语言·javascript·uni-app
deepwater_zone19 分钟前
网络爬虫(web crawler)
爬虫
看海天一色听风起雨落21 分钟前
Python学习之装饰器
开发语言·python·学习
Want59527 分钟前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客38 分钟前
c++ 杂记
开发语言·c++
jimmy.hua40 分钟前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
XiaoMu_0011 小时前
基于Python+Streamlit的旅游数据分析与预测系统:从数据可视化到机器学习预测的完整实现
python·信息可视化·旅游
THMAIL1 小时前
深度学习从入门到精通 - 生成对抗网络(GAN)实战:创造逼真图像的魔法艺术
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·cnn
w2sfot2 小时前
Passing Arguments as an Object in JavaScript
开发语言·javascript·ecmascript
郝学胜-神的一滴2 小时前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生