Python:获取新浪微博用户的收听列表和粉丝列表
在文章《Python:通过命令行发送新浪微博》中有朋友多次留言咨询用户粉丝列表获取的方法,本来不打算在写这方面的东东,但出于程序员的特有的执着,还是写一了一下。这位朋友提供了一个链接点击打开链接,其中指定了weiapi(python版本的一个缺陷),参考其先修改了下API,改后如下:parsers.py中ModelParser类的parse方法,如果你的和下面不一样,请参考修改。
class ModelParser(JSONParser):def __init__(self, model_factory=None):JSONParser.__init__(self)self.model_factory = model_factory or ModelFactorydef parse(self, method, payload):try:if method.payload_type is None: returnmodel = getattr(self.model_factory, method.payload_type)except AttributeError:raise WeibopError('No model for this payload type: %s' % method.payload_type)json = JSONParser.parse(self, method, payload)if isinstance(json, tuple):json, cursors = jsonelif isinstance(json, dict):if 'next_cursor' in json:cursors = json['next_cursor']else:cursors = Noneelse:cursors = Noneif method.payload_list:result = model.parse_list(method.api, json)else:result = model.parse(method.api, json)if cursors:return result, cursorselse:return result
2、获取列表,提供一个你要获取的用户id即可,例如我的微博ID:2601091753,用户名:没耳朵的羊,关注用户为71人,粉丝8人(悲催至极啊),如下:
3、实现代码:
#!/usr/bin/env python# -*- coding: utf-8 -*-from weibopy.auth import OAuthHandlerfrom weibopy.api import APIimport ConfigParserimport timeMAX_PIC_NUM = 5SLEEP_TIME_LONG = 30def press_sina_weibo():'''调用新浪微博Open Api实现通过命令行写博文,功能有待完善author: socratesdate:2012-02-06新浪微博:@没耳朵的羊'''sina_weibo_config = ConfigParser.ConfigParser()#读取appkey相关配置文件try:sina_weibo_config.readfp(open('sina_weibo_config.ini'))except ConfigParser.Error:print 'read sina_weibo_config.ini failed.'#获取需要的信息consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY")consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET")token = sina_weibo_config.get("userinfo","TOKEN")token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET")#调用新浪微博OpenApi(python版)auth = OAuthHandler(consumer_key, consumer_secret)auth.setToken(token, token_sercet)api = API(auth)return api;#通过命令行输入要发布的内容#weibo_content = raw_input('Please input content:')#status = api.update_status(status=weibo_content)#print "Press sina weibo successful, content is: %s" % status.text#iNum = 0#while True:# #上传图片,名称和内容如果重复,open api会检查,内容采用了取当前时间的机制# #图片名称从0-5循环遍历# status = api.upload(str(iNum)+ '.jpg', time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))# time.sleep(SLEEP_TIME_LONG)## if iNum == MAX_PIC_NUM:# iNum = 0# else:# iNum += 1def get_friends(api, user_id): '''Function:获取关注的用户列表Input:apiuser_id:指定用户的IDOutput: NONEauthor: socratesblog:http://blog.csdn.net/dyx1024date:2012-04-14''' print 'friends list: 'total_friends = 0next_cursor = -1while next_cursor != 0:timeline = api.friends(user_id,'','','',next_cursor)if isinstance(timeline, tuple):next_cursor = timelinetotal_friends += len(timeline)for line in timeline:fid = line.__getattribute__("id")name = line.__getattribute__("screen_name")text = "friends---"+ str(fid) +":"+ nametext = text.encode("gbk")print textelse:next_cursor = 0total_friends += len(timeline)for line in timeline:fid = line.__getattribute__("id")name = line.__getattribute__("screen_name")text = "friends---"+ str(fid) +":"+ nametext = text.encode("gbk")print textprint 'Total friends: %d' % total_friends def get_followers(api, user_id): '''Function:获取用户的粉丝Input:apiuser_id:指定用户的IDOutput: NONEauthor: socratesblog:http://blog.csdn.net/dyx1024date:2012-04-14''' print 'followers list: 'total_friends = 0next_cursor = -1while next_cursor != 0:timeline = api.followers(user_id,'','','',next_cursor)if isinstance(timeline, tuple):next_cursor = timelinetotal_friends += len(timeline)for line in timeline:fid = line.__getattribute__("id")name = line.__getattribute__("screen_name")text = "followers---"+ str(fid) +":"+ nametext = text.encode("gbk")print textelse:next_cursor = 0total_friends += len(timeline)for line in timeline:fid = line.__getattribute__("id")name = line.__getattribute__("screen_name")text = "followers---"+ str(fid) +":"+ nametext = text.encode("gbk")print textprint 'Total followers: %d' % total_friends def main():#获取关注列表get_friends(press_sina_weibo(), 2601091753) #获取粉丝get_followers(press_sina_weibo(), 2601091753)if __name__ == '__main__':main()
测试:friends list:friends---1248584111:曹筱燊Vfriends---1951657750:轻博客friends---2264489285:Qing官方活动friends---1650867513:365dayfriends---1296492473:单车旅行的肥猫friends---1678325381:看得见风景的记忆friends---2129867007:国家地理摄影friends---2179565352:地球人Echofriends---2447164602:小克爱家居friends---1742924093:60designwebpickfriends---2261697941:轻家居friends---1072112375:cugalafriends---1917369903:闫璐friends---2485697323:镜头中的黑白世界friends---1400314314:源形毕露friends---1629756430:LoveLomofriends---2638745273:小贤d点滴friends---1401880315:左耳朵耗子friends---1993292930:经典经济学friends---2557129567:华为中国区friends---1671248621:林正刚friends---1670481425:伯乐在线官方微博friends---1216265283:修罗陛下的微博friends---2694391504:口袋英语2012friends---1924010407:laiyonghaofriends---1784501333:数据挖掘与数据分析friends---2340488972:BalaBala_Fionafriends---1097438111:小洋洋的西红柿酱friends---1649005320:俞敏洪friends---2640459400:读书的旅程friends---1879347450:西安生活情报friends---1949305184:微博桌面friends---1894238970:developerWorksfriends---1400220917:开源中国friends---2093492691:程序员的那些事friends---1746173800:InfoQfriends---2140710271:芝雪儿friends---1100856704:余承东friends---1839167003:华为终端官方微博friends---1975995305:西安晚报friends---2202941172:陕西美食friends---1717833412:华商报friends---1750354524:西安交通旅游广播friends---1698784044:三秦都市报friends---1642909335:微博小秘书friends---1784599353:davewliufriends---1801473501:徐沛欣friends---1806762625:陈一舟friends---1798056081:万网张向东friends---1839240561:鲁明同学friends---1756644751:孙陶然friends---1497145741:杨杨杨杨杨杨杨friends---1777984105:王微friends---1749127163:雷军friends---1657288682:叶朋friends---1764529885:唐彬friends---1861284644:卢琪隆friends---1781681447:求伯君friends---1055071394:姚珏friends---1255647187:丁守谦friends---1662521105:PPS徐伟峰friends---1699907747:ChinaCache王松friends---1744303552:谢国睿friends---1657681711:潜水员庄辰超friends---1812591014:徐少春friends---1759084801:暴风冯鑫friends---1772406523:买彦州friends---1822223433:宫玉国friends---1768340073:沈博阳friends---1831348402:billgatesfriends---1670071920:史玉柱Total friends: 71followers list:followers---2463471483:吃货通followers---1097438111:小洋洋的西红柿酱followers---1659617193:在少有人走的路上followers---2386093060:朵朵奇6850followers---2340488972:BalaBala_Fionafollowers---2090442510:宁儿_YOYOfollowers---2215084900:景涛涛followers---2140710271:芝雪儿Total followers: 8
可见,与实际数目相等,列表获取完整,由于我的粉丝太少了,测试不出翻页的效果,测试了下别人的,显示正常。
页:
[1]