Skip to content

Instantly share code, notes, and snippets.

@Y4er
Last active May 9, 2019 09:38
Show Gist options
  • Save Y4er/c3912ad96cd88602e1b6b5158aa4c988 to your computer and use it in GitHub Desktop.
Save Y4er/c3912ad96cd88602e1b6b5158aa4c988 to your computer and use it in GitHub Desktop.
图床图片保存到本地
import requests
import re
import os
from datetime import datetime
COUNT = 0
def getimg(post, rule):
with open(post, 'r', encoding='utf-8') as f:
content = f.read()
imgs = re.findall(rule, content)
for markdown, img in imgs:
r = requests.get(img).content
filename = 'img/uploads/' + now() + '.jpg'
with open(filename, 'wb+')as file:
file.write(r)
global COUNT
COUNT += 1
print(filename, img)
markdown_str = markdown
markdown = markdown.replace(img, 'https://y4er.com/' + filename)
content = content.replace(markdown_str, markdown)
with open(post, 'w', encoding='utf-8')as mark:
mark.write(content)
print(post + " over! replace "+str(COUNT)+"张!")
return 0
def now():
return str(datetime.now().strftime("%Y%m%d%H") + str(datetime.now().microsecond)[-4:])
if __name__ == '__main__':
weibo = r'(!.*(https://.*sinaimg.*.jpg).*\))'
smms = r'(!.*(https://.*loli.net.*.png).*\))'
for post in os.listdir():
if post[-2:] == 'md':
with open(post, 'r', encoding='utf-8')as f:
text = f.read()
if 'sinaimg' in text:
getimg(post, weibo)
elif 'loli.net' in text:
getimg(post, smms)
else:
print(post+"没有图片")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment