前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 上传图片到简书

python 上传图片到简书

作者头像
iOSDevLog
发布2019-04-23 15:53:14
1.6K0
发布2019-04-23 15:53:14
举报
文章被收录于专栏:iOSDevLogiOSDevLog

https://gist.github.com/jiaxianhua/90d96f10074034c10145b3ca37dbfef0

代码语言:javascript
复制
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import os
from pprint import pprint

upload_url = 'https://upload.qiniup.com/'

# put cookie to cookie file
def getCookie():
    try:
        with open('cookie', 'r') as f:
            return f.readline().strip()
    except Exception as error:
        print(error)

def uploadImage(cookie, filepath):
    filename = os.path.basename(filepath)
    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': cookie,
    }

    response = requests.get(token_url, headers=headers)

    response.encoding = response.apparent_encoding
    pprint(vars(response))

    token_key = json.loads(response.text)
    pprint("token and key: {}".format(token_key))

    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)
        response.encoding = response.apparent_encoding
        img_url = json.loads(response.text)['url']
        img_md = '![{text}]({img_url})'.format(text=filename, img_url=img_url)
        return img_md

if __name__ == '__main__':
    cookie = getCookie()
    img_md = uploadImage(cookie, 'map.png')
    print(img_md)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.04.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档