在文章《 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 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人(悲催至極啊),如下:
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: 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 += 1def 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:曹筱燊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
可見,與實際數目相等,列表擷取完整,由於我的粉絲太少了,測試不出翻頁的效果,測試了下別人的,顯示正常。