zoukankan      html  css  js  c++  java
  • Python如何调用新浪api接口的问题

    前言:这些天在研究如何调用新浪开放平台的api分析新浪微博用户的数据

    成果:成功调用了新浪api获取了用户的一些个人信息和无数条公共微博

    不足:新浪开放平台访问有限制,返回的数据着实有限,不足以分析问题,真的要分析问题还是得个人写爬虫

    下面是调用新浪开放api的过程:

    第一步:按这个做就行

    http://www.cnblogs.com/dhsunny/p/3578399.html?utm_source=tuicool&utm_medium=referral

    其中有一不那个新浪api测试工具是打不开的,要自己百度

    api测试工具打开

    第二步:这是是我重点介绍一步,调用新浪api怎么获取数据,总不能在api测试工具上面弄吧,这个时候我采用的是用python

    先搭建好python开发环境,具体参考:http://www.imooc.com/learn/397

    个人建议在eclipse上面搭建,视频上有教程

    下面是调用新浪api的代码:调用的接口是

    statuses/public_timeline

    这个接口的介绍是:http://open.weibo.com/wiki/2/statuses/public_timeline
     
    代码如下:
    #coding:utf-8
    from weibo import APIClient
    import webbrowser
    import MySQLdb
    APP_KEY = '984793585' # app key
    APP_SECRET = 'ab2c926021d5cfbbc75587e67bd05a8c' # app secret
    CALLBACK_URL = 'http://weibo.com/muqingcai/home?wvr=5'# callback url       


    #利用官方微博SDK
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)


    #用得到的url到新浪页面访问
    url = client.get_authorize_url()
    webbrowser.open_new(url)


    #手动输入新浪返回的code
    code = raw_input("input the code: ").strip()


    #新浪返回的token,类似abc123xyz456,每天的token不一样
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in # token过期的UNIX时间


    #设置得到的access_token
    client.set_access_token(access_token, expires_in)


    #有了access_token后,可以做任何事情了


    #print client.statuses__public_timeline()  
    count = 1
    s = set([('mu','basketball','guangzhou','liuchuanfen')])  
    def getDataByPublic(count):
        while True:
            if count>=50:
                break
            statuses = client.statuses__public_timeline()['statuses']  
            length = len(statuses)          
            #输出了部分信息  
            for i in range(0,length):  
                nickName = statuses[i]['user']['screen_name']  
                profile = statuses[i]['user']['description']  
                location = statuses[i]['user']['location']  
                weibo = statuses[i]['text'] 
                print u'昵称:'+nickName
                print u'简介:'+profile
                print u'位置:'+location  
                print u'微博:'+weibo  
            count += 1    
    getDataByPublic(1)
     
    说明:APP_KEY 和APP_SECRET 需要在新浪开放平台上面创建应用才能获得,具体方法看第一步,CALLBACK_URL也要在应用信息的高级信息里面说明,这是回掉地址,就填你微博的首页地址
     
    运行上面程序:会弹出:
     

    输入你的微博账号密码,接着到了微博主页

     
    把code输入到控制台按回车:
    即可获得数据,这些数据可以存在数据库,也可以存到本地
     
  • 相关阅读:
    P1006 传纸条
    P1387 最大正方形
    P1417 烹调方案
    P1052 过河
    P1063 能量项链
    P1736 创意吃鱼法
    P1156 垃圾陷阱
    P1220 关路灯
    @P1373 小a和uim之大逃离
    【leetcode】Interleaving String
  • 原文地址:https://www.cnblogs.com/caimuqing/p/5662384.html
Copyright © 2011-2022 走看看