ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
 在文章[《 Python:通过命令行发送新浪微博》](http://blog.csdn.net/dyx1024/article/details/7237823#reply)中有朋友多次留言咨询用户粉丝列表获取的方法,本来不打算在写这方面的东东,但出于程序员的特有的执着,还是写一了一下。这位朋友提供了一个链接[点击打开链接](http://www.cnblogs.com/coucar/archive/2011/09/14/2176456.html),其中指定了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 ModelFactory def parse(self, method, payload): try: if method.payload_type is None: return model = 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 = json elif isinstance(json, dict): if 'next_cursor' in json: cursors = json['next_cursor'] else: cursors = None else: cursors = None if method.payload_list: result = model.parse_list(method.api, json) else: result = model.parse(method.api, json) if cursors: return result, cursors else: return result ~~~ 2、获取列表,提供一个你要获取的用户id即可,例如我的微博ID:2601091753,用户名:没耳朵的羊,关注用户为71人,粉丝8人(悲催至极啊),如下: ![](https://box.kancloud.cn/2016-06-08_5757935b64412.jpg) 3、实现代码: ~~~ #!/usr/bin/env python # -*- coding: utf-8 -*- from weibopy.auth import OAuthHandler from weibopy.api import API import ConfigParser import time MAX_PIC_NUM = 5 SLEEP_TIME_LONG = 30 def press_sina_weibo():   '''   调用新浪微博Open Api实现通过命令行写博文,功能有待完善   author: socrates   date: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 += 1 def get_friends(api, user_id):     '''   Function:获取关注的用户列表   Input:api          user_id:指定用户的ID   Output: NONE   author: socrates   blog:http://blog.csdn.net/dyx1024   date:2012-04-14   '''      print 'friends list: '   total_friends = 0   next_cursor = -1   while next_cursor != 0:       timeline = api.friends(user_id,'','','',next_cursor)       if isinstance(timeline, tuple):               next_cursor = timeline[1]               total_friends += len(timeline[0])               for line in timeline[0]:                   fid = line.__getattribute__("id")                   name = line.__getattribute__("screen_name")                   text = "friends---"+ str(fid) +":"+ name                   text = text.encode("gbk")                   print text       else:           next_cursor = 0           total_friends += len(timeline)           for line in timeline:               fid = line.__getattribute__("id")               name = line.__getattribute__("screen_name")               text = "friends---"+ str(fid) +":"+ name               text = text.encode("gbk")               print text                  print 'Total friends: %d' % total_friends           def get_followers(api, user_id):     '''   Function:获取用户的粉丝   Input:api          user_id:指定用户的ID   Output: NONE   author: socrates   blog:http://blog.csdn.net/dyx1024   date:2012-04-14   '''      print 'followers list: '   total_friends = 0   next_cursor = -1   while next_cursor != 0:       timeline = api.followers(user_id,'','','',next_cursor)       if isinstance(timeline, tuple):               next_cursor = timeline[1]               total_friends += len(timeline[0])               for line in timeline[0]:                   fid = line.__getattribute__("id")                   name = line.__getattribute__("screen_name")                   text = "followers---"+ str(fid) +":"+ name                   text = text.encode("gbk")                   print text       else:           next_cursor = 0           total_friends += len(timeline)           for line in timeline:               fid = line.__getattribute__("id")               name = line.__getattribute__("screen_name")               text = "followers---"+ str(fid) +":"+ name               text = text.encode("gbk")               print text                  print '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:曹筱燊V friends---1951657750:轻博客 friends---2264489285:Qing官方活动 friends---1650867513:365day friends---1296492473:单车旅行的肥猫 friends---1678325381:看得见风景的记忆 friends---2129867007:国家地理摄影 friends---2179565352:地球人Echo friends---2447164602:小克爱家居 friends---1742924093:60designwebpick friends---2261697941:轻家居 friends---1072112375:cugala friends---1917369903:闫璐 friends---2485697323:镜头中的黑白世界 friends---1400314314:源形毕露 friends---1629756430:LoveLomo friends---2638745273:小贤d点滴 friends---1401880315:左耳朵耗子 friends---1993292930:经典经济学 friends---2557129567:华为中国区 friends---1671248621:林正刚 friends---1670481425:伯乐在线官方微博 friends---1216265283:修罗陛下的微博 friends---2694391504:口袋英语2012 friends---1924010407:laiyonghao friends---1784501333:数据挖掘与数据分析 friends---2340488972:BalaBala_Fiona friends---1097438111:小洋洋的西红柿酱 friends---1649005320:俞敏洪 friends---2640459400:读书的旅程 friends---1879347450:西安生活情报 friends---1949305184:微博桌面 friends---1894238970:developerWorks friends---1400220917:开源中国 friends---2093492691:程序员的那些事 friends---1746173800:InfoQ friends---2140710271:芝雪儿 friends---1100856704:余承东 friends---1839167003:华为终端官方微博 friends---1975995305:西安晚报 friends---2202941172:陕西美食 friends---1717833412:华商报 friends---1750354524:西安交通旅游广播 friends---1698784044:三秦都市报 friends---1642909335:微博小秘书 friends---1784599353:davewliu friends---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:billgates friends---1670071920:史玉柱 Total friends: 71 followers list:  followers---2463471483:吃货通 followers---1097438111:小洋洋的西红柿酱 followers---1659617193:在少有人走的路上 followers---2386093060:朵朵奇6850 followers---2340488972:BalaBala_Fiona followers---2090442510:宁儿_YOYO followers---2215084900:景涛涛 followers---2140710271:芝雪儿 Total followers: 8 ~~~ 可见,与实际数目相等,列表获取完整,由于我的粉丝太少了![委屈](https://box.kancloud.cn/2016-01-25_56a5a367bba9a.gif) ,测试不出翻页的效果,测试了下别人的,显示正常。