Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

Extract data (likes) from JSON API using Python

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, weu2019ve 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:
http://twitter.com/walkers_crisps
http://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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...