Collect shared URL statistics on Facebook using Python

Asked

Viewed 183 times

6

To collect statistics from a shared Facebook URL in PHP, I am using 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 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 operation in Python?

1 answer

5


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

To manipulate the JSON, use the method loads 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, for the code to work, you need to make some changes, for example, use urllib.request.urlopen in place 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.