python调用新浪微博API

本文介绍如何使用Python版OAuth2 SDK实现新浪微博应用开发,包括获取授权码、访问令牌及调用API的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前提:在新浪微博应用开发平台成功创建一个应用,并获得可用APP_KEY、APP_SECRET、CALLBACK_URL。

1.下载OAuth2的python版SDK,https://github.com/michaelliao/sinaweibopy,其中封装的新浪微博API的文件是weibo.py;

2.使用SDK开发微博应用程序,直接上源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from weibo import *
import urllib,httplib

APP_KEY = '581******';
APP_SECRET = '99870459fe54833***********************';
CALLBACK_URL = 'http://apps.weibo.com/*********';
ACCOUNT = 'tb*******';
PASSWORD = '************';

def get_code(url):
	conn = httplib.HTTPSConnection('api.weibo.com');
	postdata = urllib.urlencode ({
		'client_id':APP_KEY,
		'response_type': 'code',
		'redirect_uri':CALLBACK_URL,
		'action':'submit',
		'userId':ACCOUNT,
		'passwd':PASSWORD,
		'isLoginSina':0,
		'from':'',
		'regCallback':'',
		'state':'',
		'ticket':'',
		'withOfficalFlag':0
	});
	conn.request('POST','/oauth2/authorize',postdata,{'Referer':url,'Content-Type': 'application/x-www-form-urlencoded'});
	res = conn.getresponse();
	#print 'headers===========',res.getheaders();
	#print 'msg===========',res.msg;
	#print 'status===========',res.status;
	#print 'reason===========',res.reason;
	#print 'version===========',res.version;
	location = res.getheader('location');
	code = location.split('=')[1];
	conn.close();
	return code;

def get_authorize():
	client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL);
	authorize_url = client.get_authorize_url();
	code = get_code(authorize_url);
	r = client.request_access_token(code);
	client.set_access_token(r.access_token, r.expires_in);
	return client;

if __name__ == '__main__':
	client = get_authorize();
	#print client.get.friendships__friends(uid='2100610530');
	#print client.get.users__show(uid=2100610530);
	#r = client.statuses.user_timeline.get();
	r = client.statuses__user_timeline();
	print r.total_number;
	for st in r.statuses:
		print st.user.screen_name;
3.SDK的使用规则:

    1)使用微博API,需要通过用户的授权,获取用户的授权码code;

    2)该SDK调用API的方法名称映射规则有以下几种,以API中的statuses/public_timeline接口为例:

        a)client.get.statuses__public_timeline(),将"/"换为两个"_",注意是两个。同时根据请求是POST还是GET,使用get或者post;

        b)client.statuses__public_timeline(),对于GET方式,在调用API时,可以将get省略;

        c)client.statuses.public_timeline.get(),将API中的"/"更换为".",同时最后指定是get方式还是post方式。

    3)参数问题:如果API中有参数指定,则在方法中提供参数;

    4)返回值:新浪返回的结果是JSON,但是SDK将其封装成了JSON对象,直接通过返回结果调用相应的属性即可。例如:

{
    "statuses": [
        {
            "created_at": "Tue May 31 17:46:55 +0800 2011",
            "id": 11488058246,
            "text": "求关注。",
            "source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
            "favorited": false,
            "truncated": false,
            "in_reply_to_status_id": "",
            "in_reply_to_user_id": "",
            "in_reply_to_screen_name": "",
            "geo": null,
            "mid": "5612814510546515491",
            "reposts_count": 8,
            "comments_count": 9,
            "annotations": [],
            "user": {
                "id": 1404376560,
                "screen_name": "zaku",
                "name": "zaku",
                "province": "11",
                "city": "5",
                "location": "北京 朝阳区",
                "description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。",
                "url": "http://blog.sina.com.cn/zaku",
                "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
                "domain": "zaku",
                "gender": "m",
                "followers_count": 1204,
                "friends_count": 447,
                "statuses_count": 2908,
                "favourites_count": 0,
                "created_at": "Fri Aug 28 00:00:00 +0800 2009",
                "following": false,
                "allow_all_act_msg": false,
                "remark": "",
                "geo_enabled": true,
                "verified": false,
                "allow_all_comment": true,
                "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",
                "verified_reason": "",
                "follow_me": false,
                "online_status": 0,
                "bi_followers_count": 215
            }
        },
        ...
    ],
    "previous_cursor": 0,                    // 暂未支持
    "next_cursor": 11488013766,     // 暂未支持
    "total_number": 81655
}
对于该返回的JSON格式,r为SDK的返回结果,则通过r.statuses即可获取JSON中的statuses列表,r.total_number获取JSON中的total_number属性,r.statuses[0].user.id获得statuses列表第一个元素的user对象中的id。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值