Extract data (likes) from JSON API using Python

a 夏天 提交于 2019-12-13 05:51:16

问题


I want to pull the number of likes for my project.

Here's my code:

import facepy
from facepy import GraphAPI
from bs4 import BeautifulSoup
import json
access = 'CAACEdEose0cBAE3IL99IreDeAfqaVZBOje8ZCqIhf6tPaf7HsPF3J9DYRWi3YuSTf0HXQwr2LMAgczDBWBSDNFzHrEjxzkBQ9hbZCYC1fB2z1qyHs5BeAZCV3zyU8JhEcbSiiB5Bf73gZAfQ1rUa2pdx9U24dUZCX0qMDzvXHLHV9jPRiZBByB2b2uEHGk22M4ZD'
graph = GraphAPI(access)
page_id= 'walkers'
datas= graph.get(page_id+'/', page=True, retry=5)
for data in datas:
    print data

And here's the output:

  {
    u'category': u'Product/Service',
    u'username': u'walkers',
    u'about': u"Welcome to the home of Walkers Crisps. When it comes to making Brits smile, we\u2019ve got it in the bag (yeah, we went there.) We're here Mon-Fri, 9am-6pm!",
    u'talking_about_count': 3076,
    u'description': u'To find out more about Walkers, visit:\nhttp://twitter.com/walkers_crisps\nhttp://www.youtube.com/walkerscrisps',
    u'has_added_app': False,
    u'can_post': True,
    u'cover': {
      u'source': u'https://scontent.xx.fbcdn.net/hphotos-xpt1/t31.0-8/s720x720/11165156_10153204315777649_4115137634691483959_o.jpg',
      u'cover_id': u'10153204315777649',
      u'offset_x': 0,
      u'offset_y': 0,
      u'id': u'10153204315777649'
    },
    u'name': u'Walkers',
    u'website': u'http://www.walkers.co.uk',
    u'link': u'https://www.facebook.com/walkers',
    u'likes': 552762,
    u'parking': {
      u'street': 0,
      u'lot': 0,
      u'valet': 0
    },
    u'is_community_page': False,
    u'were_here_count': 0,
    u'checkins': 0,
    u'id': u'53198517648',
    u'is_published': True
  }

I want to pull the number of likes, preferably just the number. How would one go about doing this?


回答1:


As this is a generator, there's no good way to get a specific element. You can either iterate over it and check for each element if it's the one you're looking for, or, if you will need more than one element from it, convert it into a dictionary.

This is one way to convert it:

new_dictionary = {}
for name, value in datas:
    new_dictionary[name] = value

With this you could then get likes with:

likes = new_dictionary['likes']

Or if you only want to get 'items' from it:

for name, value in datas:
    if name == 'likes':
        likes = value



回答2:


import facepy
from facepy import GraphAPI    
from bs4 import BeautifulSoup    
import json

access = 'CAACEdEose0cBAE3IL99IreDeAfqaVZBOje8ZCqIhf6tPaf7HsPF3J9DYRWi3YuSTf0HXQwr2LMAgczDBWBSDNFzHrEjxzkBQ9hbZCYC1fB2z1qyHs5BeAZCV3zyU8JhEcbSiiB5Bf73gZAfQ1rUa2pdx9U24dUZCX0qMDzvXHLHV9jPRiZBByB2b2uEHGk22M4ZD'

graph = GraphAPI(access)

page_id= 'walkers'

datas= graph.get(page_id+'/', page=True, retry=5)

likes = datas['likes']

print likes


来源:https://stackoverflow.com/questions/31782942/extract-data-likes-from-json-api-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!