思路很简单:就是给本地的图片上传到图床上,然后再复制过来,就没问题了。
    代码:

    1. import requests
    2. from requests_toolbelt.multipart.encoder import MultipartEncoder
    3. import random
    4. import re
    5. import urllib
    6. import time
    7. from tqdm import tqdm
    8. def upload2danke(filePath): # https://imgkr.com/
    9. filename = filePath.split("/")[-1]
    10. ck_time = str(time.time())[:10]
    11. url = "https://imgkr.com/api/files/upload"
    12. cookies = {"_ga": "GA1.2.1950159671.{}".format(ck_time), "_gid": "GA1.2.1236723023.{}".format(ck_time)}
    13. headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0",
    14. "Accept": "*/*", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
    15. "X-Requested-With": "XMLHttpRequest", "Origin": "https://imgkr.com", "Connection": "close",
    16. "Referer": "https://imgkr.com/"}
    17. data = MultipartEncoder(
    18. fields={
    19. "file": (filename, open(filePath, 'rb'), 'application/octet-stream')
    20. },
    21. boundary="-----------------------------{}".format(random.randint(1e13, 1e14 - 1)))
    22. headers['Content-Type'] = data.content_type
    23. req = requests.post(url, headers=headers, cookies=cookies, data=data)
    24. res = req.json()
    25. if res['code'] == 200:
    26. return res['data']
    27. else:
    28. return None
    29. # 提取markdown中的其他链接
    30. def extractUrl(markdown_file_path):
    31. f = open(markdown_file_path, 'rb')
    32. markdown_content = f.read()
    33. f.close()
    34. url_regex = b"!\[.*?\]\((.*?)\)"
    35. all_image_url = re.findall(url_regex, markdown_content)
    36. all_image_url = [image.decode('utf-8', 'ignore') for image in all_image_url]
    37. return all_image_url
    38. # 将旧链接替换为新链接,前面为旧的图片url集合,后面为新的url集合,替换后写入 原来的文档名_new 中
    39. def exchange_url(markdown_file_path, all_image_url, all_danke_image_url):
    40. f = open(markdown_file_path, 'rb')
    41. markdown_content = f.read()
    42. f.close()
    43. # 替换
    44. for old_img, new_img in zip(all_image_url, all_danke_image_url):
    45. markdown_content = markdown_content.replace(old_img.encode(), new_img.encode())
    46. # 写入
    47. f = open(f"{markdown_file_path}.txt", 'wb')
    48. f.write(markdown_content)
    49. f.close()
    50. print(f"save at {markdown_file_path}.txt")
    51. if __name__ == '__main__':
    52. markdown_file_path = input("markdown file path: ")
    53. markdown_path = markdown_file_path.replace(markdown_file_path.split("/")[-1], "") # 后面拼接图片变成绝对路径
    54. all_image_url = extractUrl(markdown_file_path)
    55. all_unquote_image_url = [urllib.parse.unquote(img) for img in all_image_url] # URL解码,不然路径识别可能存在问题
    56. all_danke_image_url = [upload2danke(markdown_path+img) for img in tqdm(all_unquote_image_url, desc="上传中", ncols=100)]
    57. exchange_url(markdown_file_path, all_image_url, all_danke_image_url)

    image.png
    image.pngs