说来有意思,最近一段时间经常在逛论坛,但是实际上论坛上看看最近的一些帖子有改动的帖子优点不太方便。所以突发灵感,我可以通过关注论坛的大部分人,来获取到他们的动态就行了。
实现
这里就直接贴代码来,代码其实很好看懂
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import json
ACCESSTOKEN = "56dc9b566bb2d3a05b4c2f919e4d6492ee4b8b1a7e4ce7921c3579xxxxxxx"
REFRESHTOKEN = "f6f211474440a7e9019b76de6ce81535558bb84c290665bb6bedfab22a15bcd3"
HOSTADDR = "https://testerhome.com/api/v3/"
class MyHttpRequest(object):
def __init__(self):
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(self.opener)
def get_response(self, url, data = None,customCookies=None):
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
if data is not None:
req = urllib2.Request(url, urllib.urlencode(data))
else:
req = urllib2.Request(url)
req.add_header('User-Agent', user_agent)
req.add_header('Accept-Encoding', '*')
if customCookies is not None:
req.add_header("Cookie", customCookies)
response = self.opener.open(req)
return response
def getActivitiesUser():
'''
获取论坛活跃的人目前取前100个
'''
content_page = myHttpRequest.get_response(HOSTADDR+"users?limit=100").read().decode("utf-8")
return json.loads(content_page)['users']
def getFollowOrFollowingUsers(login,isFollowing=None):
'''
获取关注者
'''
# login = userlist[-1]['login']
followers = []
offset = 0
print 'get',login,'follower'
while 1:
if isFollowing is None:
url = HOSTADDR + "users/"+login+"/followers.json?limit=100&offset="+ str(offset)
keyword = 'followers'
else:
url = HOSTADDR + "users/"+login+"/following.json?limit=100&offset="+ str(offset)
keyword = 'following'
content_page = myHttpRequest.get_response(url).read().decode("utf-8")
followList = json.loads(content_page)[keyword]
if len(followList)==0:
break
else:
offset += len(followList)
for follow in followList:
followers.append(follow['login'])
if len(followList) < 100:
break
return followers
def follow(login):
'''
关注用户
'''
url = HOSTADDR + "/users/" + login + "/follow.json?"
postData = {
"login":login,
"access_token":ACCESSTOKEN
}
print myHttpRequest.get_response(url,postData).read().decode("utf-8")
myFollowers.append(login)
def getFollowerAndFollow(login):
'''
获取关注者以及正在关注的对象并判断是否在列表中不在则进行关注操作
'''
if login in checkUser:
return
followers = getFollowOrFollowingUsers(login)
followingers = getFollowOrFollowingUsers(login,True)
checkUser.append(login)
for follower in followers:
if follower not in myFollowers and follower!=login:
print 'follow',follower
follow(follower)
if follower!='zsx10110':
getFollowerAndFollow(follower)
for follower in followingers:
if follower not in myFollowers and follower!=login:
print 'follow',follower
follow(follower)
if follower!='zsx10110':
getFollowerAndFollow(follower)
checkUser = ['zsx10110']
myHttpRequest= MyHttpRequest()
myFollowers = getFollowOrFollowingUsers("zsx10110",True)
print len(myFollowers)
userlist = getActivitiesUser()
for user in userlist:
getFollowerAndFollow(user['login'])
关于如何获取到access_token 的话可以查看另外一篇文章 使用Postman进行outh2认证