简体   繁体   中英

Count likes on a Facebook post using Python+Facebook Graph API

I want to count how many times a friend has liked a user's post using Python.

I have successfully fetched the names of friends who have liked the posts. But there are some posts which don't have any like at all. The code gives an error there. I'm using facebook-sdk 1.0.0 . Any help would be much appreciated. Code snippet is:

import facebook
graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")
for w in range (0,5):
    p1=posts['data'][w]['likes']['data']
    for i in range (0,len(p1)):
      r=p1[i]['name']
      print(r) 

Also, Is there any way to find out the list of friends hitting maximum likes on all posts?

I am a little unsure on exactly what you are missing here or what your question is, but it looks like all you need to do is define the name you want to look for and count how many times it occurs in your code.

Something like this:

import facebook

likes = 0 # How many times they likes on your posts 
friend = "Bob" # Your friends name   

graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")
for w in range (0,5):
    p1=posts['data'][w]['likes']['data']
    for i in range (0,len(p1)):
      if friend == p1[i]['name']
          likes += 1
print likes

Also, you could clean up your code considerably if you ditched the ranges for your for loops and instead iterated over the data structures themselves. Something like this would work:

import facebook

likes = 0 # How many times they likes on your posts 
friend = "Bob" # Your friends name   

graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")

for user_post in posts['data']:
    for name in user_post['likes']['data']:
      if friend == name['name']
          likes += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM