python代码模块,依赖requests库

爬取wallhaven随机图库前24张图并存储在目标路径

import requests
import re
import os

header = {}
header['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'


class Wallpaper:

    def __init__(self):
        for root, dirs, files in os.walk('D:/Chromed/wallpaper/'):     # 删除目录下已存在的图片(是你幻灯片存放所在的目录)
            for i in files:
                path = 'D:/Chromed/wallpaper/' + i                     # 这里也要改
                os.remove(path)
        self.get_picture_url('https://alpha.wallhaven.cc/random')

    def get_picture_url(self, url):
        try:
            response = requests.get(url, headers=header)
        except requests.exceptions.ConnectionError:
            print('get wrong')
            return
        res = r'class="preview" href=".+?"  target="_blank"  >'
        res = re.compile(res)
        res_text = re.findall(res, response.text)
        for i in res_text:
            res = re.compile(r'https.+?"')
            res = re.findall(res, i)
            res = res[0][0:-1]
            self.spider(res)

    def spider(self, url):
        try:
            response = requests.get(url, headers=header)
        except requests.exceptions.ConnectionError:
            print('get wrong')
            return
        res = r'<meta property="og:image" content=".+?" />'
        res = re.compile(res)
        res_text = re.findall(res, response.text)
        for i in res_text:
            res = re.compile(r'//wallpapers.+?"')
            res = re.findall(res, i)
            res = 'https:' + res[0][:-1]
            self.download(res)

    @staticmethod
    def download(url):
        try:
            response = requests.get(url, headers=header)
        except requests.exceptions.ConnectionError:
            print('get wrong')
            return
        file = 'D:/Chromed/wallpaper/' + url[-20:]   # url[-20:]为图片的名字,前面为其目录,可自行更改
        try:
            with open(file, 'wb') as f:
                f.write(response.content)
        except:
            print('save wrong')
        text = url + '  正在下载,请不要关闭'
        print(text)


wallpaper = Wallpaper()

注:D:/Chromed/wallpaper/ 为我幻灯片的目录,请修改为您所在的目录

设置幻灯片

桌面右键个性化,设置背景为幻灯片放映,相册为爬虫存储目标文件夹
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸

设置定时任务

打开计划任务Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
点击创建基本任务,设置名称、触发器、操作Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
最后一步设置程序或脚本为您的python目录下python.exe
添加参数为您的爬虫脚本的目录
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸
设置好之后,便会定时执行脚本,更换幻灯片目录下的所有图片
Python爬取wallhaven,设置定时任务每日更换幻灯片壁纸

相关文章:

  • 2021-05-31
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2021-11-23
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-31
  • 2022-02-01
  • 2022-12-23
  • 2021-11-03
  • 2022-12-23
  • 2021-06-29
  • 2021-05-29
相关资源
相似解决方案