python新浪api_python调用新浪微博API | 学步园

前提:在新浪微博应用开发平台成功创建一个应用,并获得可用APP_KEY、APP_SECRET、CALLBACK_URL。1.下载OAuth2的python版SDK,https://github.com/michaelliao/sinaweibopy,其中封装的新浪微博API的文件是weibo.py;2.使用SDK开发微博应用程序,直接上源码:#!/usr/bin/env python# -*- c...
摘要由CSDN通过智能技术生成

前提:在新浪微博应用开发平台成功创建一个应用,并获得可用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": "新浪微博",

"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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解如何使用 Python 模拟登录新浪微博。这是一个比较复杂的过程,需要使用到一些网络编程技术。以下是大致的步骤: 1. 打开新浪微博登录页面,获取登录页面的 HTML 代码。 2. 解析登录页面的 HTML 代码,获取登录所需的参数,如登录表单的 action、用户名和密码的 input 标签名称等。 3. 构造 POST 请求,将用户名和密码等参数以表单形式提交给登录表单的 action 地址。 4. 发送 POST 请求,获取登录后的页面 HTML 代码。 5. 解析登录后的页面 HTML 代码,判断登录是否成功。 以下是一个简单的示例代码,可以帮助您更好地理解该过程: ```python import requests from bs4 import BeautifulSoup # 1. 获取登录页面的 HTML 代码 login_url = 'https://weibo.com/login.php' response = requests.get(login_url) html = response.text # 2. 解析登录页面的 HTML 代码,获取登录所需的参数 soup = BeautifulSoup(html, 'html.parser') login_action = soup.find('form', attrs={'name': 'loginform'})['action'] login_username = soup.find('input', attrs={'name': 'username'})['name'] login_password = soup.find('input', attrs={'name': 'password'})['name'] # 3. 构造 POST 请求,将用户名和密码等参数以表单形式提交给登录表单的 action 地址 data = { 'username': 'your_username', 'password': 'your_password', 'savestate': '1', 'r': '', 'ec': '0', 'pagerefer': '', 'entry': 'mweibo', 'mainpageflag': '1' } post_url = f'https://weibo.com/{login_action}' response = requests.post(post_url, data=data) # 4. 发送 POST 请求,获取登录后的页面 HTML 代码 html = response.text # 5. 解析登录后的页面 HTML 代码,判断登录是否成功 soup = BeautifulSoup(html, 'html.parser') if soup.find('a', attrs={'title': '我的首页'}): print('登录成功') else: print('登录失败') ``` 需要注意的是,该示例代码中使用了 requests 库和 BeautifulSoup 库,需要安装后才能运行。此外,登录过程可能会因为验证码等原因而变得更加复杂,需要您自行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值