在记录学习过程中发现写下的md文档在更新至简书时,文档中的本地图片无法正常上传成功,不管时富文本模式还是md模式,所以在找解决方式的过程中发现一些方法,只能手动插入每一张图片,在找的的时候很费劲,所以在网上找了一些方法:
1.使用github图床
具体过程可以参考 Github做图床
在使用时发现需要一张一张的上传图片得到一个图片链接,个人觉得还是很费劲,可能时自己不太会用
2.使用程序打开md文档找到图片,将图片使用简书上传图片的接口上传得到一个图片url,然后替换文档中的本地图片地址:
作者: tristan_lee
对应文章:自动将md文档中的图片上传到简书
该文章中使用了python实现了这个过程,所以就参考了他的方式,实现了图片上传的功能。
具体步骤:
1.可以使用抓包工具或者谷歌浏览器F12,查看自己简书账号的 cookies ,然后将 cookies 复制出保存为cookies.txt文件,cookies有效期过期可以重新获取。
浏览器步骤:
点击Console,输入指令 document.cookie,回车即可显示出当前页面cookie信息
name=value; name=value; name=value; name=value;
2.在使用的时候发现不成功,所以做了一点小小的修改,cookies读取的值是整个cookies内容,并没有按照如下方式,
# get cookie from cookie file
def getCookie(path):
try:
with open(path, 'r') as f:
content = f.readlines()
for line in content:
cook = line.split(';')
if len(cook) > 1:
break
cookies = ''
for str in cook:
if str.find('token') != -1:
cookies += str+';'
if str.find('uid') != -1:
cookies += str+';'
if str.find('sensorsdata') != -1:
cookies += str+';'
return cookies
except Exception as error:
print(error)
而是将抓包获得的cookies 全部传入:
def getCookie(path):
try:
with open(path, 'r') as f:
content = f.readline()
return content.strip()
except Exception as error:
print(error)
3.请求报https验证错误,增加关闭ssl验证的标志verify=False
response = requests.get(token_url, headers=headers, verify=False)
response = requests.post(upload_url, headers=headers, files=files, verify=False)
4.最后运行运行脚本,替换完后会输出新文件output.md
replace_md.py xxx.md
基本流程:
- 使用正则匹配出md文档中的图片位置
- 根据图片位置的链接
- 如果是本地图片地址,直接上传,返回图片链接
- 如果是网络图片链接,先下载再上传,返回图片链接
- 用返回的图片链接替换md文档中原来的图片位置
下面为我修改后的代码,源码来自于作者作者: tristan_lee
#!/usr/bin/env python3
import requests
import json
import os
import sys
import datetime
import re
import imghdr
import _locale
_locale._getdefaultlocale = (lambda *args: ['zh_CN', 'utf8'])
cookie_file = 'cookies.txt'
upload_url = 'https://upload.qiniup.com/'
# get cookie from cookie file
def getCookie(path):
try:
with open(path, 'r') as f:
content = f.readline()
return content.strip()
except Exception as error:
print(error)
def uploadImage(cook_path, filepath, name='img'):
cookStr = getCookie(cook_path)
#print(cookStr)
filename = os.path.basename(filepath)
fname,suffix=os.path.splitext(filepath)
if suffix == '':
suffix = imghdr.what(filepath)
filename = fname+'.'+suffix
token_url = 'https://www.jianshu.com/upload_images/token.json?filename={}'.format(filename)
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
'Cookie': cookStr,
}
response = requests.get(token_url, headers=headers, verify=False)
response.encoding = response.apparent_encoding
token_key = json.loads(response.text)
if 'token' not in token_key:
return None
with open(filepath, 'rb') as file:
files = {
'file': (filename, file),
'token': (None, token_key['token']),
'key': (None, token_key['key']),
}
response = requests.post(upload_url, headers=headers, files=files, verify=False)
response.encoding = response.apparent_encoding
img_url = json.loads(response.text)['url']
img_md = '![{text}]({img_url})'.format(text=name, img_url=img_url)
return img_md
def outputFile(path):
try:
with open(path, 'r') as fd, open("output.md", "w") as fd1:
tmpPath = '__tmp__'
content = fd.readlines()
for line in content:
# match http link image
obj = re.search( r'!\[(.*)\]\((http.+)\)', line)
if obj:
name = obj.group(1)
filePath = obj.group(2)
with open(tmpPath, 'wb') as tmpFd:
ir = requests.get(filePath)
tmpFd.write(ir.content)
newline = uploadImage(cookie_file, tmpPath, name)
if newline is None:
print('Err: ', 'uploadImage() error!')
else:
print('Ok: ', 'uploadImage() ok!')
line = newline
fd1.write(line)
continue
# match local file image
obj = re.search( r'!\[(.*)\]\((.+)\)', line)
if obj:
name = obj.group(1)
filePath = obj.group(2)
newline = uploadImage(cookie_file, filePath, name)
if newline is None:
print('Err: ', 'uploadImage() error!')
else:
print('Ok: ', 'uploadImage() ok!')
line = newline
fd1.write(line)
if os.path.exists(tmpPath):
os.remove(tmpPath)
return None
except Exception as error:
print('err:', error)
def main(path):
if os.path.exists(path):
outputFile(path)
return True
else:
print("File path %s not exist!" % (path))
return False
if __name__ == '__main__':
if len(sys.argv) <= 1:
print("Usage error: replace_md.py %path")
sys.exit(-1)
else:
main(sys.argv[1])
sys.exit(0)
参考:
网友评论