微博图床 Python

import requests
import json
import re


def subString(rule, text):
    slotList = re.findall(rule, text)
    return slotList


def work(img_path):
    imgBytes = bytes()
    with open(img_path, 'rb') as f:
        imgBytes = f.read()
    url = 'https://picupload.weibo.com/interface/pic_upload.php?s=json&ori=1&data=1&rotate=0&wm=&app=miniblog&mime=image%2Fpng'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
        'Cookie': 'SUB=' # 这里将你登录后的sub值填入进去
    }
    res = requests.post(url=url, headers=headers, data=imgBytes)
    res_text = '{"code"%s}}}}' % subString(r'{"code"(.*?)}}}}', res.text)[0]
    # print(res_text)
    res_json = json.loads(res_text)
    print(res_json)
    if res_json['code'] == 'A00006':
        # 成功
        pid = res_json["data"]["pics"]["pic_1"]["pid"]
        return {
            'code': res_json['code'],
            'raw': {
                'url': f'http://tvax2.sinaimg.cn/large/{pid}.jpg',
                'url_ssl': f'https://tva1.sinaimg.cn/large/{pid}.jpg',
                'width': res_json["data"]["pics"]["pic_1"]['width'],
                'height': res_json["data"]["pics"]["pic_1"]['height'],
                'size': res_json["data"]["pics"]["pic_1"]['size'],
            },
            'small': {
                'url': f'http://tva3.sinaimg.cn/mw690/{pid}.jpg',
                'url_ssl': f'https://tva3.sinaimg.cn/mw690/{pid}.jpg'
            },
            'mini': {
                'url': f'http://tva2.sinaimg.cn/thumbnail/{pid}.jpg',
                'url': f'https://tvax1.sinaimg.cn/thumbnail/{pid}.jpg'
            }
        }
    elif res_json['code'] == 'A20001':
        # 失败
        pass
    else:
        # 失败
        pass
    return {'code': res_json['code']}


if __name__ == '__main__':
    img_path = input('请输入图片路径: ')
    res = work(img_path)
    print(json.dumps(res, indent=2))

关于过时问题, 使用如下代码解决, 需要用到两个参数, alf和alc, 在登录时可以抓包到这两个参数, relogin后返回的新sub参数可以用作请求参数

def reLogin(alf, alc):
    session = requests.session()
    userAgent = {
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like  Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.36accept:text/html,   application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,   application/signed-exchange;v=b3;q=0.9'
    }
    def get(url, headers={}):
        if not headers.get('Cookie'):
            session.headers.update(
                {'Referer': 'https://login.sina.com.cn/sso/login.php'})
        return session.get(url=url,
                           headers=headers,
                           allow_redirects=False,
                           verify=False)

    session.trust_env = False
    headers = {'Cookie': f'ALF={alf};', }
    headers.update(userAgent)
    # 1.获取Location
    res = get(url='https://weibo.com/', headers=headers)
    location = res.headers['Location']
    if location.find('login.sina.com.cn/sso/login.php') == -1:
        print('[1]获取Location失败')
        return 1

    # 2.跳转location
    headers['Cookie'] = f'ALC={alc};'
    res = get(url=location, headers=headers)
    url = subString(r'\("(.*?)"\);', res.text)
    if len(url) == 0:
        print('[2]跳转location 未找到url')
        return 2
    SUB = subString(r'SUB=(.*?);', res.headers["Set-Cookie"])
    if len(SUB) == 0:
        print('[2]跳转location 未找到sub')
        return 3
    SUB = f"SUB={SUB[0]}; "

    # 3.获取crossdomain2地址
    url = subString(r'replace\(\"(.*?)\"', res.text)
    if len(url) == 0:
        print('[3]未找到crossdomain2地址', res.text)
        return 4
    url = url[0]

    # 4.获取passport.weibo.com/wbsso/login?ticket=
    res = get(url=url)
    url = subString(r'\[\"(.*?)\"', res.text)
    if len(url) == 0:
        print('[4]获取wbsso/login地址失败', res.text)
        return 5
    url = url[0].replace('\/', '/')

    # 5.跳转passport.weibo.com/wbsso/login?ticket=
    res = get(url=url)
    SUB = subString(r'SUB=(.*?);', res.headers['Set-Cookie'])
    if len(SUB) == 0:
        print('[5]获取SUB失败')
        return 6
    SUB = SUB[0]
    return SUB

发表回复