如何使用Python對(duì)Instagram進(jìn)行數(shù)據(jù)分析?-36大數(shù)據(jù)
作者: Nour Galaby
我寫此文的目的在于展示以編程的方式使用Instagram的基本方法。我的方法可用于數(shù)據(jù)分析、計(jì)算機(jī)視覺以及任何你所能想到的酷炫項(xiàng)目中。
Instagram是最大的圖片分享社交媒體平臺(tái),每月活躍用戶約五億,每日有九千五百萬(wàn)的圖片和視頻被上傳到Instagram。其數(shù)據(jù)規(guī)模巨大,具有很大的潛能。本文將給出如何將Instagram作為數(shù)據(jù)源而非一個(gè)平臺(tái),并介紹在項(xiàng)目中使用本文所給出的開發(fā)方法。
API和工具簡(jiǎn)介
我推薦使用Jupyter Notebook和IPython。使用官方Python雖然沒有問(wèn)題,但是它不提供圖片顯示等特性。
安裝
你可以使用pip安裝該軟件庫(kù),命令如下:
python -m pip install -e git+https://github.com/LevPasha/Instagram-API-python.git#egg=InstagramAPI
如果系統(tǒng)中尚未安裝ffmpeg,那么在Linux上,可以使用如下命令安裝:
sudo apt-get install ffmpeg
對(duì)于Windows系統(tǒng),需在Python解釋器中運(yùn)行如下命令:
import imageio imageio.plugins.ffmpeg.download()
下面使用API,實(shí)現(xiàn)登入Instragram:
from InstagramAPI import InstagramAPI username="YOURUSERNAME" InstagramAPI = InstagramAPI(username, "YOURPASSWORD") InstagramAPI.login()
如果登錄成功,那么你會(huì)收到“登陸成功”的消息。
基本請(qǐng)求
做好上面的準(zhǔn)備工作后,我們可以著手實(shí)現(xiàn)首次請(qǐng)求:
InstagramAPI.getProfileData() result = InstagramAPI.LastJson
{u'status': u'ok', u'user': {u'biography': u'', u'birthday': None, u'country_code': 20, u'email': aaa@hotmail.com', u'external_url': u'', u'full_name': u'Nour Galaby', u'gender': 1, u'has_anonymous_profile_picture': False, u'hd_profile_pic_url_info': {u'height': 1080, u'url': u'https://instagram.fcai2-1.fna.fbcdn.net/t51.2885-1aaa7448121591_1aa.jpg', u'width': 1080}, u'hd_profile_pic_versions': [{u'height': 320, u'url': u'https://instagram.fcai2-1.fna.fbcdn.net/t51.2885-19/s320x320/19aa23237_4337448121591_195310aaa32_a.jpg', u'width': 320}, {u'height': 640, u'url': u'https://instagram.fcai2-1.fna.fbcdn.net/t51.2885-19/s640x640/19623237_45581744812153_44_a.jpg', u'width': 640}], u'is_private': True, u'is_verified': False, u'national_number': 122, u'phone_number': u'+201220', u'pk': 22412229, u'profile_pic_id': u'1550239680720880455_22', u'profile_pic_url': u'https://instagram.fcai2-1.fna.fbcdn.net/t51.2885-19/s150x150/19623237_455817448121591_195310166162_a.jpg', u'show_conversion_edit_entry': False, u'username': u'nourgalaby'}}
如上所示,結(jié)果是以JSON格式給出的,其中包括了所有請(qǐng)求的數(shù)據(jù)。
你可以使用正常的鍵值方式訪問(wèn)結(jié)果數(shù)據(jù)。例如:
你也可以使用工具(例如Notepad++)查看JSON數(shù)據(jù),并一探究竟。
獲取并查看Instagram時(shí)間線
下面讓我們實(shí)現(xiàn)一些更有用的功能。我們將請(qǐng)求排在時(shí)間線最后的帖子,并在Jupyter Notebook中查看。
下面代碼實(shí)現(xiàn)獲取時(shí)間線:
InstagramAPI.timelineFeed()
類似于前面的請(qǐng)求實(shí)現(xiàn),我們同樣使用LastJson()查看結(jié)果。查看結(jié)果JSON數(shù)據(jù),我們可以看到其中包括一系列稱為“條目”的鍵值。列表中的每個(gè)元素保存了時(shí)間線上特定帖子的信息,其中包括如下元素:
- [text]:保存了標(biāo)題下的帖子文本內(nèi)容,包括hashtag。
- [likes]:帖子中的點(diǎn)贊數(shù)。
- [created_at]:帖子創(chuàng)建時(shí)間。
- [comments]:帖子的評(píng)論。
- [image_versions]:保存有指向?qū)嶋HJPG文件的鏈接,可使用該鏈接在Jupyter Notebook中顯示圖片。
函數(shù)
函數(shù)Get_posts_from_list()和Get_url()在帖子列表上循環(huán),查找每個(gè)帖子中的URL,并附加到我們的空列表中。
上述函數(shù)完成后,我們將得到一個(gè)URL列表,如下所示:
我們可以使用IPython.display模塊查看圖片,代碼如下:
在IPython Notebook中查看圖片是十分有用的功能,我們之后還會(huì)使用這些函數(shù)去查看結(jié)果,敬請(qǐng)繼續(xù)。
獲取最受歡迎的帖子
現(xiàn)在我們已經(jīng)知道了如何發(fā)出基本請(qǐng)求,但是如何實(shí)現(xiàn)更復(fù)雜的請(qǐng)求呢?下面我們要做一些類似的事情,即如何獲取我們的帖子中最受歡迎的。要實(shí)現(xiàn)這個(gè)目的,首先需要獲取當(dāng)前登錄用戶的所有帖子,然后將帖子按點(diǎn)贊數(shù)排序。
獲取用戶的所有帖子
要獲取所有帖子,我們將使用next_max_id和more_avialable值在結(jié)果列表上執(zhí)行循環(huán)。
import time myposts=[] has_more_posts = True max_id="" while has_more_posts: InstagramAPI.getSelfUserFeed(maxid=max_id) if InstagramAPI.LastJson['more_available'] is not True: has_more_posts = False #stop condition print "stopped" max_id = InstagramAPI.LastJson.get('next_max_id','') myposts.extend(InstagramAPI.LastJson['items']) #merge lists time.sleep(2) # Slows the script down to avoid flooding the servers print len(myposts)
保存和加載數(shù)據(jù)到磁盤
因?yàn)樯厦娴恼?qǐng)求可能需要很長(zhǎng)的時(shí)間才能完成,我們并不想在沒有必要時(shí)運(yùn)行它,因此好的做法是將結(jié)果保存起來(lái),并在繼續(xù)工作時(shí)再次加載。為此,我們將使用Pickle。Pickle可以將任何變量序列化并保存到文件中,進(jìn)而加載它們。下面給出一個(gè)工作例子:
保存:
import pickle filename=username+"_posts" pickle.dump(myposts,open(filename,"wb"))
加載:
import pickle filename="nourgalaby_posts" myposts=pickle.load(file=open(filename))
按點(diǎn)贊數(shù)排序
現(xiàn)在我們得到了一個(gè)名稱為“myposts”的有序字典。要實(shí)現(xiàn)根據(jù)字典中的某個(gè)鍵值排序,我們可以使用Lambda表達(dá)式,代碼如下:
myposts_sorted = sorted(myposts, key=lambda k: k['like_count'],reverse=True) top_posts=myposts_sorted[:10] bottom_posts=myposts_sorted[-10:]
如下代碼可以實(shí)現(xiàn)和上面一樣的顯示:
image_urls=get_images_from_list(top_posts) display_images_from_url(image_urls)
過(guò)濾圖片
我們可能想要對(duì)我們的帖子做一些過(guò)濾。例如,可能有的帖子中是視頻,但是我們只想要圖片帖子。我們可以這樣做過(guò)濾:
myposts_photos= filter(lambda k: k['media_type']==1, myposts) myposts_vids= filter(lambda k: k['media_type']==2, myposts) print len(myposts) print len(myposts_photos) print len(myposts_vids)
當(dāng)然,你可以對(duì)結(jié)果中的任何變量做過(guò)濾,發(fā)揮你的創(chuàng)造力吧!
通知
InstagramAPI.getRecentActivity() get_recent_activity_response= InstagramAPI.LastJson for notifcation in get_recent_activity_response['old_stories']: print notifcation['args']['text']
結(jié)果可能是:
userohamed3 liked your post. userhacker32 liked your post. user22 liked your post. userz77 liked your post. userwww77 started following you. user2222 liked your post. user23553 liked your post.
僅來(lái)自特定用戶的通知
現(xiàn)在,我們可以按我們的要求操作并玩轉(zhuǎn)通知。例如,我可以獲得來(lái)自于特定用戶的通知列表:
username="diana" for notifcation in get_recent_activity_response['old_stories']: text = notifcation['args']['text'] if username in text: print text
讓我們嘗試一些更有意思的操作,例如:得到你被點(diǎn)贊最多的時(shí)刻,一天中何時(shí)人們點(diǎn)贊最多。要實(shí)現(xiàn)這些操作,我們將繪制一個(gè)關(guān)系圖,顯示一天中的時(shí)刻和你所收到點(diǎn)贊數(shù)的關(guān)系。
下面的代碼繪制了通知的時(shí)間日期:
import pandas as pd df = pd.DataFrame({"date":dates}) df.groupby(df["date"].dt.hour).count().plot(kind="bar",title="Hour" )
正如在此例中所看到的,我在下午六點(diǎn)到十點(diǎn)間得到的點(diǎn)贊最多。如果你了解社交媒體,你就會(huì)知道這是高峰使用時(shí)間,大多數(shù)企業(yè)選取此時(shí)間段發(fā)帖以獲得最大的認(rèn)可度。
獲取粉絲和被粉列表
下面我將獲取粉絲和跟帖列表,并在列表上執(zhí)行一些操作。
要使用getUserFollowings和getUserFollowers這兩個(gè)函數(shù),你首先需要取得user_id。下面給出了一種獲取user_id的方式:
現(xiàn)在你可以如下調(diào)用函數(shù)。注意,如果粉絲數(shù)量非常大,你需要做多次請(qǐng)求(下文將詳細(xì)介紹)。現(xiàn)在我們做了一次請(qǐng)求去獲取粉絲和被粉列表。JSON結(jié)果中給出了用戶列表,其中包含每個(gè)粉絲和被粉者的信息。
InstagramAPI.getUserFollowings(user_id) print len(InstagramAPI.LastJson['users']) following_list=InstagramAPI.LastJson['users'] InstagramAPI.getUserFollowers(user_id) print len(InstagramAPI.LastJson['users']) followers_list=InstagramAPI.LastJson['users']
如果粉絲數(shù)量很大,那么給出的結(jié)果可能并非完整列表。
獲得所有的粉絲
獲得所有粉絲列表類似于獲得所有帖子。我們將發(fā)出一個(gè)請(qǐng)求,然后對(duì)結(jié)果使用next_max_id鍵值做迭代處理。
在此感謝Francesc Garcia所提供的支持。
import time followers = [] next_max_id = True while next_max_id: print next_max_id #first iteration hack if next_max_id == True: next_max_id='' _ = InstagramAPI.getUserFollowers(user_id,maxid=next_max_id) followers.extend ( InstagramAPI.LastJson.get('users',[])) next_max_id = InstagramAPI.LastJson.get('next_max_id','') time.sleep(1) followers_list=followers
對(duì)于被粉列表也可以同樣做,但是我并不會(huì)這樣做,因?yàn)榫臀叶裕淮握?qǐng)求就足以獲取我的所有被粉者。
現(xiàn)在我們得到了JSON格式的所有粉絲和被粉者的列表數(shù)據(jù)。我將轉(zhuǎn)化該列表為一種對(duì)用戶更友好的數(shù)據(jù)類型,即集合,以方便在數(shù)據(jù)上做一系列的操作。
我只取其中的“username”鍵值,并在其上使用set()。
user_list = map(lambda x: x['username'] , following_list) following_set= set(user_list) print len(following_set) user_list = map(lambda x: x['username'] , followers_list) followers_set= set(user_list) print len(followers_set)
這里我選取了所有用戶名的集合。對(duì)“full_name”也可同樣操作,并且結(jié)果更為用戶友好。但是結(jié)果可能并非唯一,因?yàn)橐恍┯脩艨赡軟]有提供全名。
現(xiàn)在我們得到了兩個(gè)集合。我們可以做如下操作:
這里我給出了粉絲的一些統(tǒng)計(jì)數(shù)字。你可以做很多事情,例如保存粉絲列表并稍后做對(duì)比,以了解掉粉的情況。
上面我們給出了可對(duì)Instagram數(shù)據(jù)進(jìn)行的操作。我希望你已經(jīng)學(xué)會(huì)了如何使用Instagram API,并具備了一些使用這些API可以做哪些事情的基本想法。敬請(qǐng)關(guān)注一下官方API,它們依然在開發(fā)中,未來(lái)你可以使用它們做更多的事情。如有任何疑問(wèn)或建議,歡迎聯(lián)系我。
End.
轉(zhuǎn)載請(qǐng)注明來(lái)自36大數(shù)據(jù)(36dsj.com): 36大數(shù)據(jù) ? 如何使用Python對(duì)Instagram進(jìn)行數(shù)據(jù)分析?