python 高清壁纸下载

import os
import re
from urllib import request
import json

url = "http://www.2800.so/pic/api.php?cid=360new&start=0&count=30"
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"}


class Pic(object):
    def __init__(self, name, file_name, content):
        self.name = name
        self.dir = file_name
        self.content = content

    def save_content(self):
        os.makedirs(self.dir, exist_ok=True)  # 创建文件目录,文件存在不会报错
        path = ''.join([self.dir, '/', self.name, '.jpg'])
        try:
            with open(path, 'xb') as f:# x模式创建一个新的文件,如果文件存在,会报错
                f.write(self.content)
        except Exception:
            print("在文件已经存在")


class SpiderWallpaper(object):
    def __init__(self, url):
        self.url = url

    def get_response(self, url):
        req = request.Request(url, headers=headers)
        response = request.urlopen(req)
        if response.status == 200:
            return response

    def get_content(self, url, tag):
        response = self.get_response(url)
        return (response.read(), tag)

    def get_pic_url(self, res):
        for i in res:
            url = i['url']
            tag = "".join(re.split(r'[_a-z\s]+', i['tag']))
            item = self.get_content(url, tag)
            file_name = '壁纸'
            content, name = item
            yield Pic(tag, file_name, content)

    def main(self):
        url = self.url
        response = self.get_response(url)
        res = json.loads(response.read(), encoding='utf-8')
        content_list = res['data']
        res_list = []
        for i in self.get_pic_url(content_list):
            res_list.append(i)
        return res_list

    def __iter__(self):
        for i in self.main():
            yield i


for i in SpiderWallpaper(url):
    i.save_content()
    

你可能感兴趣的:(python,爬虫)