Python保存图床图片到本地

Share on:

新浪图床挂了之后我的博客图片挂了一大堆,今天写了个脚本来解决下。

 1import requests
 2import re
 3import os
 4from datetime import datetime
 5
 6COUNT = 0
 7
 8
 9def getimg(post, rule):
10    with open(post, 'r', encoding='utf-8') as f:
11        content = f.read()
12        imgs = re.findall(rule, content)
13        for markdown, img in imgs:
14            r = requests.get(img).content
15            filename = 'img/uploads/' + now() + '.jpg'
16            with open(filename, 'wb+')as file:
17                file.write(r)
18                global COUNT
19                COUNT += 1
20                print(filename, img)
21            markdown_str = markdown
22            markdown = markdown.replace(img, 'https://y4er.com/' + filename)
23            content = content.replace(markdown_str, markdown)
24        with open(post, 'w', encoding='utf-8')as mark:
25            mark.write(content)
26            print(post + " over! replace "+str(COUNT)+"张!")
27    return 0
28
29
30def now():
31    return str(datetime.now().strftime("%Y%m%d%H") + str(datetime.now().microsecond)[-4:])
32
33
34if __name__ == '__main__':
35    weibo = r'(!.*(https://.*sinaimg.*.jpg).*\))'
36    smms = r'(!.*(https://.*loli.net.*.png).*\))'
37    for post in os.listdir():
38        if post[-2:] == 'md':
39            with open(post, 'r', encoding='utf-8')as f:
40                text = f.read()
41                if 'sinaimg' in text:
42                    getimg(post, weibo)
43                elif 'loli.net' in text:
44                    getimg(post, smms)
45                else:
46                    print(post+"没有图片")