使用Python对Instagram进行数据分析

时间:2022-05-02
本文章向大家介绍使用Python对Instagram进行数据分析,主要内容包括关于API和工具、安装、使用API登录到Instagram、简单请求、获得并查看Instagram时间线、功能、获得帖子排行榜、获得所有用户的帖子、保存/加载数据到磁盘上、按点赞数量排序、过滤照片、通知、只有一个用户的通知、获得跟踪用户和跟踪列表、获取所有的跟踪用户、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Instagram是最大的照片分享社交媒体平台,每月有5亿活跃用户,每天会上传9500万张照片和视频到Instagram上。它有大量的数据和巨大的潜力。这篇文章将教会你如何使用Instagram作为数据的来源,以及如何将它作为你的项目的开发者。

关于API和工具

Instagram有一个官方的API,但它已经过时了,目前在你能用它做的事情非常有限。因此,在这篇文章中,我将使用LevPasha的非官方Instagram API,它支持所有的主要功能,如follow,上传照片和视频等。它是用Python编写的。

我推荐使用Jupyter笔记本和IPython。普通的python运行良好,但可能没有显示图像的功能。

安装

你可以使用pip来安装库:

python-m pip install-e git+https://github.com/LevPasha/Instagram-API-python.git#egg=InstagramAPI

你可能需要ffmpeg。在Linux上安装它

sudo apt-get install ffmpeg

对于Windows,在Python解释器中运行它

import imageio
imageio.plugins.ffmpeg.download()

使用API登录到Instagram

from InstagramAPIimport InstagramAPI
username="YOURUSERNAME"
InstagramAPI= InstagramAPI(username,"YOURPASSWORD")
InstagramAPI.login()

如果登录成功,你会收到“登录成功”的提示信息。

简单请求

有了这些,就从我们的第一个请求开始:

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'}}

正如你所看到的,结果是JSON 格式,包含了所有的请求数据

你可以以键/值方式访问它。例如:

你可以使用任何先进的查看工具(Notepad++)查看JSON并研究它。

获得并查看Instagram时间线

现在让我们做一些更有趣的事情。我们请求时间线上最后的帖子,并在我们的笔记本上查看。

有了这条线,你就可以得到时间线:

InstagramAPI.timelineFeed()

并且类似于先前的请求,我们将使用LastJson()来查看结果。通过检查生成的JSON,我们可以看到它包含一个名为“items”的键。 该列表中的每个单元包含有关时间轴中特定帖子的信息,包括以下单元:

  • [text] – 标题的文本值保存在帖子下面,包括标签
  • [likes] – 点赞的数量
  • [created_at] – 创建帖子的日期
  • [comments] – 发表评论
  • [image_versions] – 包含实际JPG文件的链接,我们可以在Jupyter笔记本上显示它。

功能

Get_posts_from_list()和Get_url()将循环访问帖子列表,找到每个帖子的URL并将其添加到空列表中:

完成后,我们应该有如下的URL列表:

我们可以使用Ipython.display模块查看图片,显示如下

在笔记本中查看图像是非常有用的,我们稍后将使用这些函数来查看我们的结果,正如你将看到的那样。

获得帖子排行榜

我们需要得到我们最喜欢的帖子。为了做到这一点,首先我们需要在你的用户配置文件中获得所有的帖子,然后根据点赞的数量对它们进行排序。

获得所有用户的帖子

为了获得所有的帖子,我们将使用next_max_id和more_avialabl的值循环访问结果列表。

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)

保存/加载数据到磁盘上

请求可能会花费很长一段时间,所以不必要的时候我们不会运行它。但当我们持续工作的时候,保存结果并加载它们是一种不错的方法。为此,我们将使用Pickle。Pickle可以序列化任何变量,将其保存到文件中,然后加载它。这里有一个例子说明它是如何工作的。

保存:

import pickle
filename=username+"_posts"
pickle.dump(myposts,open(filename,"wb"))

加载:

import pickle
filename="nourgalaby_posts"
myposts=pickle.load(file=open(filename))

按点赞数量排序

现在我们有了一个名为“myposts”的字典的列表。由于我们要按照字典内的某个键对它进行排序,我们可以这样使用lambda表达式:

myposts_sorted= sorted(myposts, key=lambda k:
k['like_count'],reverse=True)
top_posts=myposts_sorted[:10]
bottom_posts=myposts_sorted[-10:]

然后显示它们

image_urls=get_images_from_list(top_posts)
display_images_from_url(image_urls)

过滤照片

我们可能想把一些过滤器应用到我们的帖子列表中。例如,我只想要图片,但在帖子中有视频,,我可以这样过滤:

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)

当然,你可以对结果中的任何变量应用过滤器。

通知

InstagramAPI.getRecentActivity()
get_recent_activity_response= InstagramAPI.LastJson
for notifcationin get_recent_activity_response['old_stories']:
    print notifcation['args']['text']

你可以看见一些东西,比如

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.

只有一个用户的通知

在这一点上,我们可以像我们希望的那样操作和播放通知。例如,我可以得到只有一个特定用户的通知列表:

username="diana"
for notifcationin get_recent_activity_response['old_stories']:
    text= notifcation['args']['text']
    if username in text:
        print text

我们尝试一些更有趣的东西:让我们看看你最喜欢的时间,和一天中人们最喜欢的时间。为了完成这件事,我们需要绘图。

import pandas as pd
df= pd.DataFrame({"date":dates})
df.groupby(df["date"].dt.hour).count().plot(kind="bar",title="Hour" )

正如你所看到的,最受欢迎的时间段是18:00-22:00,如果你使用社交媒体,你就会知道这是一个社交媒体使用的高峰时间,大多数公司选择这个时间发布消息以获得最多的参与。

获得跟踪用户和跟踪列表

我将获得跟踪用户和跟踪列表,并对其进行一些操作。为了使用getUserFollowings和getUserFollowers这两个函数,你需要先获取user_id。你可以这样获取user_id:

现在你可以简单地使用以下功能。请注意,如果跟踪用户数量很多,你需要执行多个请求(下一个更多)。在这里,我们提出了一个请求来获得跟踪用户/跟踪列表。JSON结果包含“用户”列表,其中包含每个跟踪用户/跟踪列表的所有信息。

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']

如果数量很大,这个结果可能没有完整的集合。

获取所有的跟踪用户

获得跟踪用户的列表类似于得到所有的帖子。我们将发出一个请求,然后使用next_max_id键进行迭代:

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

你应该重复同样的操作以得到跟踪列表,但在这种情况下,我不会这样做,因为一个请求就已经做够得到我案例中所有的跟踪列表。

现在,我们有了一个JSON格式的跟踪用户和跟踪列表的所有数据,我将把它们转换成更友好的数据类型–set–,以便对它们执行一些设置操作。

我会使用 ‘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)

在这里,我为每个用户创建一组保护用户名。“full_name”也可以工作,而且更友好,但一些用户可能不具有full_name的值。

现在我们有了两个集合,进行下面的操作:

我们有一些关于跟踪用户的统计数据。你可以从这一点做很多事情,例如保存跟踪列表,然后在稍后的时间比较它以获得unfollower的列表。

这些都是你可以用Instagram数据做的事情。我希望你学会如何使用Instagram的API,并知道能用它做什么。保持独创性的眼光,因为它还在发展中,将来你还可以做更多的事情。