<file_sep>"""知乎图片"""
import re
import json
import requests
import os
import time
from pathlib import Path
path = "./pics"
url = 'https://www.zhihu.com/question/58498720'
class Pics(object):
    """
        下载知乎问题下所有回答图片
        example：pic = Pics('https://www.zhihu.com/question/270912691', './pics')
                 pic.run()
    """
    def __init__(self, url, path):
        self.header = {
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3551.3 Safari/537.36',
            'Upgrade-Insecure-Requests':'1',
            'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        }
        # 问题
        self.index_url = url
        # 获取问题的json链接
        # https://www.zhihu.com/api/v4/questions/58498720/answers?include=content&limit=20&offset=0&sort_by=default
        self.url = self.makeUrl(url)
        # 存放根目录路径
        self.base_dir = Path(path)
        self.page = None
        self.makeNewSession()
    
    def makeUrl(self, url):
        rindex = url.rfind('/') + 1
        answers_url = 'https://www.zhihu.com/api/v4/questions/' + url[rindex:] + '/answers'

        return answers_url
    def makeNewSession(self):
        """用于保持cookies"""
        self.session = requests.session()
        self.session.headers = self.header
        params = {
            "include":"content",
            "limit":"20",
            "offset":"0",
            "sort_by":"default",
        }
        self.session.params = params
        self.session.get(self.index_url)

    def getContent(self):
        """获取图片"""
        print('正在从%s下载'%self.url)
        json_str = self.session.get(self.url)
        json_obj = json.loads(json_str.content.decode())

        data = json_obj.get('data')

        if data:
            self.url = json_obj.get('paging').get('next')
        else:
            self.url = ''

        for i in data:
            self.formatPic(i.get('content'), i.get("id"))
        

    def formatPic(self,content,answer_id):
        result = list(set(re.findall(r'data-original="(.+?)"', content))) #正则获取图片 然后去重
        answer_id = str(answer_id)
        index = 0
        for i in result:
            path = self.makePicName(i, index, answer_id)
            index +=1

            pic = self.session.get(i)
            if pic.status_code != 200:
                print('图片：'+i+'获取失败')
                print('状态码：'+pic.status_code)
                time.sleep(3)
            self.savePic(pic,path)

    def savePic(self,pic,name):
        with Path(self.base_dir/name).open("wb") as f:
            f.write(pic.content)
            print('保存图片:'+self.base_dir.parts[-1]+'/'+name)

    def makePicName(self,link,index,answer_id):
        rindex = link.rfind(".")
        name = '{}_{}{}'.format(answer_id,index,link[rindex:])
        return name

    def run(self):
        is_exists = self.base_dir.exists()
        if not is_exists:
            self.base_dir.mkdir()
        while True:
            if self.url == '':
                break
            self.getContent()

        print('图片下载完毕')

if __name__ == '__main__':
    pic = Pics(url, path)
    pic.run()<file_sep># spider
### 抓取知乎问题下所有图片
```
from　zhihu_pic import Pics 
pic = Pics("问题链接", "存放位置")
```
