您的位置:首页 > 编程语言 > Python开发

python学习之女神追追追(二)代码阶段

2015-01-09 21:03 369 查看
上文中我们做好了准备工作,接下来我们开始写响应的代码

首先是原理,如果我们想实时获得一个人的微博是否更新,那我们需要不断地轮询他的微博

微博api列表中我发现有一个叫做friends_timeline的接口(其实以前直接用user_timeline就好了,但是渣浪官方好像封掉这个端口了)

微博api的工作方法是,通过产生一个包含appkey,appsecret和callback(回调)的地址,点击后跳转到另一个链接,我们需要获得其中的"code"值,我们需要通过代码来实现,如下

APP_KEY = "adasdadadasd38"
APP_SECRET = 'badadadasdasb7c92409a'
CALLBACK = 'http://127.0.0.1:5000/aaa'#这个要和在网站上注册的回调地址相同才行

client = weibo.APIClient(APP_KEY,APP_SECRET,CALLBACK)
auth_url = client.get_authorize_url()


当我们访问author_url的时候,就会自动回调一个地址



你可以通过某种方式获得这段code并把它保存在变量code中(我是采用直接写了各网页然后通过get方式得到这个值)

r = client.request_access_token(code)
client.set_access_token(r.access_token,r.expires_in)


接下来我们就能访问api了

例如我想查看我所有关注的人的微博,那我就调用home_timeline的api



weibo_nr= client.statuses.home_timeline.get(count="50")


注意看上面那一段和上图的关系,其实就是吧url中2后面的"/"换成"."即可调用,然后get或者post中换成"name=value"方式即可,渣浪文档还是足够全的(返回值"weibo_nr"是json类型的直接可以解析)

好的,放出我的代码来,我是通过抓取timeline前50条,从中筛选出女神的id,然后获得mid(应该是类似每条微博的id的东西),获得并存储在一个列表中,如果下一次轮询中女神id的第一条mid不在这个列表中,说明有了新微博,那么立刻调用api上去评论

weibo_perfect.py代码

#coding=utf-8
import weibo
import time
from flask import Flask, request, render_template, redirect, url_for
from random import choice
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

APP_KEY = "adadad8"#填上你的appkey
APP_SECRET = 'b2asdsadadasdasdadas'#填上你的appsecret
CALLBACK = 'http://127.0.0.1:5000/aaa'

comment_list = ['抢占头条','坐沙发','前排','抢沙发','前排围观','火钳刘明']
app = Flask(__name__)
@app.route('/')
def get_code():
return render_template('weibo.html')
@app.route('/aaa', methods=['GET'])
def run():
client = weibo.APIClient(APP_KEY,APP_SECRET,CALLBACK)
auth_url = client.get_authorize_url()
code = request.args.get('code').encode("utf-8")
print "get code!"
r = client.request_access_token(code) client.set_access_token(r.access_token,r.expires_in)
comment_old = 0
mid_pool = []
while True:
weibo_nr= client.statuses.friends_timeline.get(count="50")
for x in weibo_nr["statuses"]:
if x["user"]["id"] == ???????1:#填上目标的用户id
if len(mid_pool) == 0:
mid_pool.append(x["mid"])
break
else:
mid_target = x["mid"]
print "x[mid] = "+str(mid_target)
if mid_target in mid_pool:
print "nothing happend"
break
else:
print "get new weibo!!"
comment = choice(comment_list)
while comment_old==comment:
comment = choice(comment_list)
client.comments.create.post(comment=comment,id=mid_target)
print "success!! mid = "+str(mid_target)
mid_pool.append(mid_target)
comment_old = comment
break
print "search already done"
else:
print "He's not the target"
time.sleep(4)
return "Done"
if __name__ == "__main__":
app.run(debug=True)


其中用户id可以看用户的微博主页



格式是weibo.com/u/后面的那穿数字

weibo.html的代码是

<html>
<head></head>
<body>
<a href="https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//127.0.0.1%3A5000/aaa&response_type=code&client_id=此处填写你的appkey">点我开始</a>

</body>

</html>


运行时



访问http://127.0.0.1:5000/即可,教程愉悦的结束了~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: