设为首页 收藏本站
查看: 1058|回复: 0

[经验分享] Python:获取新浪微博用户的收听列表和粉丝列表

[复制链接]
发表于 2017-5-8 09:36:16 | 显示全部楼层 |阅读模式
  在文章《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人(悲催至极啊),如下:
DSC0000.jpg

  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 = 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) +":"+ 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 = 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) +":"+ 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
可见,与实际数目相等,列表获取完整,由于我的粉丝太少了 DSC0001.gif ,测试不出翻页的效果,测试了下别人的,显示正常。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-374490-1-1.html 上篇帖子: python获取当前日期前后N天或N月的日期[转] 下篇帖子: Python——maketrans和translate方法,可以用来从string中替换和删除字符
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表