2

I want to get all comments of a facebook post. We can extract comments by passing the limit() in Api call But how we know the limit? I need all comments.

https://graph.facebook.com/10153608167431961?fields=comments.limit(100).summary(true)&access_token=LMN  

By using this

data = graph.get_connections(id='10153608167431961', connection_name='comments')

I am getting few comments. How can I get all comments of a post?

Edit

import codecs
import json
import urllib

import requests
B = "https://graph.facebook.com/"
P ="10153608167431961"
f = "?fields=comments.limit(4).summary(true)&access_token="
T = "EAACb6lXwZDZD"
url = B+P+f+T


def fun(data):

    nextLink =  (data['comments']['paging']['next'])
    print(nextLink)
    for i in data['comments']['data']:
        print (i['message'])

    html = urllib.request.urlopen(nextLink).read()
    data = json.loads(html.decode('utf-8'))
    fun(data)

html = urllib.request.urlopen(url).read()
d = json.loads(html.decode('utf-8'))

fun(d)

It is giving the error

KeyError: 'comments'

Amar
  • 855
  • 5
  • 17
  • 36

1 Answers1

0

You need to implement paging to get all/more comments: https://developers.facebook.com/docs/graph-api/using-graph-api/#paging

Usually, this is done with a "recursive function", but you have to keep in mind that you may hit API limits if there are a LOT of comments. It´s better to load more comments on demand only.

Example for JavaScript: How does paging in facebook javascript API work?

Community
  • 1
  • 1
andyrandy
  • 72,880
  • 8
  • 113
  • 130
  • Can you refer me to a working example of getting anything from facebook using pagination? – Amar Sep 10 '16 at 13:07
  • just take a look at the SO link in my answer, there is an example with javascript. you just need to do recursive calls to the "next" link, which is a simple api call. – andyrandy Sep 10 '16 at 13:16
  • I am working in python. I never work with javascript. :) – Amar Sep 10 '16 at 13:22
  • recursive functions are a basic programming concept, there are probably thousands of examples available with google. for example: http://stackoverflow.com/questions/479343/how-can-i-build-a-recursive-function-in-python – andyrandy Sep 10 '16 at 14:00
  • and when you know how to write a recursive function, the rest is straightforward, just look at the first link in my answer. in every api call, you get a "next" link, which is the api call for the next result batch. – andyrandy Sep 10 '16 at 14:01
  • I tried to implement the recursion but it is giving the error. Would you like to see the **Edit** in Question? – Amar Sep 11 '16 at 09:58
  • i don´t know much about pyhton, but you should debug "data". i guess the error means that data["comments"] cannot be found. – andyrandy Sep 11 '16 at 10:49