最新消息:

python sdk读取weibo粉丝列表

api admin 3107浏览 0评论
#!/usr/bin/env python
#coding=utf8

from weibo import APIClient
import urllib
import urllib2
import httplib
import re


def get_code():
    ''' 自动获取code '''
    conn = httplib.HTTPSConnection('api.weibo.com')
    params = urllib.urlencode({
    'action':'submit',
    'withOfficalFlag':'0',
    'ticket':'',
    'isLoginSina':0,
    'response_type':'code',
    'regCallback':'',
    'redirect_uri':REDIRECT_URL,
    'client_id':APP_KEY,
    'state':'',
    'from':'',
    'userId':USERID,
    'passwd':USERPASSWD,
    })
    conn.request('POST','/oauth2/authorize', params, {'Referer': url, 'Content-Type': 'application/x-www-form-urlencoded'})
    res = conn.getresponse()
    for line in res.msg.headers:
        if re.search('Location', line):
            return line.strip().split('=')[1]
    conn.close()

def get_fans(code):
    fans_list = []
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    client.set_access_token(access_token, expires_in)
    next_cursor = 0
    total_fans = client.friendships.followers.get(uid=UID, cursor=next_cursor, count=10)['total_number']
    us = client.friendships.followers.get(uid=UID, cursor=next_cursor, count=total_fans)['users']
    for u in us:
        fans_list.append(u)
    return total_fans, fans_list

if name == 'main':
    APP_KEY = 'xxxxxxxxx'
    APP_SECRET = 'xxxxxxxxxxxxxxxxxxxx'
    REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'
    USERID = 'username'
    USERPASSWD = 'password'
    UID = 'xxxxxxxxx'
    url = 'https://api.weibo.com/oauth2/authorize?redirect_uri=%s&response_type=code&client_id=%s&display=default' % (urllib.quote(REDIRECT_URL), APP_KEY)
    c = get_code()
    total_fans, fans_list = get_fans(c)
    print '粉丝数: %s' % total_fans
    for fans in fans_list:
        print '%s\t%s' % (fans['id'], fans['screen_name'])

转载请注明:爱开源 » python sdk读取weibo粉丝列表

您必须 登录 才能发表评论!