Collect shared URL statistics on Facebook using Python

5

To collect statistics from a shared URL on Facebook in PHP, I'm making use of cURL to query the following URI:

// URL para submeter
$pageUrl = 'http://www.example.com/my-new-article-is-neat';

// URI a consultar
$uri = 'https://graph.facebook.com/fql?q=';
$uri.= urlencode("SELECT like_count, total_count, share_count, click_count, comment_count FROM link_stat WHERE url = \"{$pageUrl}\"");

/* cURL it
 */
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $uri
));

$resp = curl_exec($curl);

curl_close($curl);

Where do we get:

{
   "data": [
      {
         "like_count": 0,
         "total_count": 0,
         "share_count": 0,
         "click_count": 0,
         "comment_count": 0
      }
   ]
}

Then we can use the result as follows:

$respObj = json_decode($resp);

var_dump($respObj->data[0]->total_count); // int(0)

Question

How can I perform the same Python operation?

    
asked by anonymous 09.04.2015 / 14:37

1 answer

4

You can use urllib.quote_plus to format the URL and urllib.urlopen to make the request and get the response.

To manipulate JSON , use the loads of the module json .

import urllib, json

def obterEstatisticas(url):
    parametros = urllib.quote_plus('SELECT like_count, total_count, share_count, click_count, comment_count FROM link_stat WHERE url = "{0}"'.format(url))
    facebookURL = 'https://graph.facebook.com/fql?q={0}'.format(parametros)
    resposta = urllib.urlopen(facebookURL).read()
    return resposta

def main():
    url = 'http://www.example.com/my-new-article-is-neat'
    estatisticas = json.loads(obterEstatisticas(url))
    total_count = estatisticas['data'][0]['total_count']
    print (total_count)

main()

Exemplo

In Python 3, it is necessary to make some changes, for example, to use urllib.request.urlopen instead of urllib.urlopen .

from urllib import parse, request
import json

def obterEstatisticas(url):
    parametros = parse.quote_plus('SELECT like_count, total_count, share_count, click_count, comment_count FROM link_stat WHERE url = "{0}"'.format(url))
    facebookURL = 'https://graph.facebook.com/fql?q={0}'.format(parametros)
    resposta = request.urlopen(facebookURL).read()
    return resposta

def main():
    url = 'http://www.example.com/my-new-article-is-neat'
    estatisticas = json.loads(obterEstatisticas(url).decode())
    total_count = estatisticas['data'][0]['total_count']
    print (total_count)

main()

Exemplo

    
11.04.2015 / 01:20