目标1:后台发微博,查看关系链等 第一步 成为开发者http://dev.t.qq.com/需要填入一些基本的信息,如身份证号码等。 第二步: 创建应用,选择站内应用-非托管 ,主要是为了拿到appk
目标1:后台发微博,查看关系链等
第一步
成为开发者 http://dev.t.qq.com/ 需要填入一些基本的信息,如身份证号码等。
第二步:
创建应用,选择站内应用-非托管 ,主要是为了拿到appkey和app secret
第三步:
下载SDK http://wiki.open.t.qq.com/index.php/SDK%E4%B8%8B%E8%BD%BD
python SDK在这里 https://github.com/wbopenplatform/PY-SDK
第四步:
编写脚本,只运行 get_access_token()函数,获取到一个url,打开url,授权后获得新的url,获得ACCESS_TOKEN和OPENID的值。
第五步:
运行脚本的tweibo_test()函数,即可操作你的微博发消息或者查看你的粉丝,查看你关注的人。
# -*- coding:utf-8 -*- ##! /usr/bin/env pythonimport timeimport urllib import urllib2 from tweibo import *#首先要创建自己的应用,换成你的 APPKEY http://dev.t.qq.com/APP_KEY = "801475XXX" APP_SECRET = "e52f7267447c3ccbcf7884809dbdXXXX"CALLBACK_URL = "my.oschina.net/sanpeterguo"#你的应用会去得到某个微博t.qq.com/peterguo的授权,获得方法即执行get_access_token即可获得一个url,这个url用浏览器打开,授权后连接地址中会增加ACESS_TOKEN参数,拿出来。ACCESS_TOKEN = "06611ad81a58d8f517f614426f2XXXXX";OPENID="30A1ACF2E94E5835A83D57CB80XXXXXX"IMG_EXAMPLE = "example.png"#调用API只需要上面的五个参数 APP_KEY APP_SECRET CALLBACK_URL ACCESS_TOKEN OPENID# 返回text是unicode,设置默认编码为utf8import sysreload(sys)sys.setdefaultencoding('utf8')def get_access_token(): oauth = OAuth2Handler() oauth.set_app_key_secret(APP_KEY, APP_SECRET, CALLBACK_URL) print oauth.get_access_token_url() def tweibo_test(): oauth = OAuth2Handler() oauth.set_app_key_secret(APP_KEY, APP_SECRET, CALLBACK_URL) oauth.set_access_token(ACCESS_TOKEN) oauth.set_openid(OPENID) api = API(oauth) if False: #获取t.qq.com/qqfarm 的三条微博 ret = api.get.statuses__user_timeline(format="json", name="qqfarm", reqnum=3, pageflag=0, lastid=0, pagetime=0, type=3, contenttype=0) print ret.data.info[0]['text'] #获取自己的信息 http://test.open.t.qq.com/#friends/idollist if False: #知道微博id,获取自己的某条微博内容,查看该微博的id,打开源码找: <ul id="talkList" class="LC"><li id="338597029252485" rel #view-source:http://t.qq.com/peterguo/mine api.get.t__show(format="json", id=338597029252485).data.text api.get.t__list(ids=[338597029252485, 338597029252485]) if False: #获取peterguo的粉丝 ret = api.get.friends__user_fanslist(name='peterguo') #print ret.data.info[0]['name'] print "Peterguo s fans......" for dItem in ret.data.info: print dItem['name'] if False: #获取自己的偶像列表 print "Peterguo s idols ......" ret = api.get.friends__idollist(name="peterguo", reqnum=20, pageflag=2) #print ret.data.info[5]['name'] for dItem in ret.data.info: print dItem['name'] if False: #发微博 api.post.t__add(content='hi python') #发带图的微博,先上传图,获取到图片url,再发微博 # UPLOAD /t/upload_pic pic1 = api.upload.t__upload_pic(format="json", pic_type=2, pic=open(IMG_EXAMPLE, "rb")) print ">> IMG: %s" % (pic1.data.imgurl) # POST /t/add_pic_url content_str2 = "哈哈哈 demo: %s, time %s" % (IMG_EXAMPLE, time.time()) pic_urls = "%s" % (pic1.data.imgurl) tweet_pic1 = api.post.t__add_pic_url(format="json", content=content_str2, pic_url=pic_urls) print ">> time=%s, http://t.qq.com/p/t/%s" % (tweet_pic1.data.time, tweet_pic1.data.id) #双向收听的 nCount = 0 lCrawNames = ["waxjwaxj", "peterguo", "joliexu"] if len(sys.argv) != 1: lCrawNames = sys.argv[1:] for craw_name in lCrawNames: nIdx = 0 while True: time.sleep(3) try: ret = api.get.friends__mutual_list(name=craw_name, reqnum=10, pageflag=1, startindex=nIdx) except tweibo.TWeiboError: break for dItem in ret.data.info: nCount += 1 try: print nCount, dItem['name'], " -> ", dItem['nick'] fp = file("src.txt", "at") fp.write("%s:%s:%s/n" %(craw_name, dItem['name'], dItem['nick'])) fp.close() except Exception,e: print e nIdx += 10 if __name__ == "__main__": tweibo_test()
目标2:生成的数据如果配合networkx 进行计算绘图:
如下是计算笔者,笔者妻子和一个同事的微博互粉关系图:
代码:
#-*- coding:utf8-*-import networkx as nximport matplotlib.pyplot as pltG = nx.Graph()#G.add_nodes_from([3,4,5,6])#G.add_edges_from([(3,5),(3,6),(6,7)])def loadFile2List(strFilename): ''' load a file and return content as list, every item is a line, except "#" ''' retLst = [] try: fp = file(strFilename, "rt") except IOError: assert(False) return retLst while True: line = fp.readline() if len(line) == 0: break; if line.startswith('#') or line == '/r/n' or line == '/n': continue line = line.strip() retLst.append(line) return retLst srcLst = loadFile2List("src.txt")dName2ListFriends = {}for strLine in srcLst: lSptLine = strLine.split(":") if lSptLine == "": continue if not (lSptLine[0] in dName2ListFriends.keys()): dName2ListFriends[lSptLine[0]] = [] dName2ListFriends[lSptLine[0]].append(lSptLine[1])print dName2ListFriends lNodes = []lEdges = []for strKeyName in dName2ListFriends.keys(): lNodes.append(strKeyName) for strName in dName2ListFriends[strKeyName]: lNodes.append(strName) lEdges.append((strKeyName, strName))lNodes = list(set(lNodes))lEdges = list(set(lEdges))print lEdges#raw_input("pause")G.add_nodes_from(lNodes)G.add_edges_from(lEdges)nx.draw(G)plt.savefig("wuxiangtu.png")plt.show()
参考1:https://github.com/upbit/tweibo-pysdk/wiki/demo.py%E8%AF%A6%E8%A7%A3
参考2:https://github.com/upbit/tweibo-pysdk/wiki/OAuth2Handler