Question:
To collect the statistics of a URL shared on Facebook, 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?
Answer:
You can use the urllib.quote_plus
functions to format the URL and urllib.urlopen
to make the request and get the response.
To manipulate JSON , we use the json
module's loads
method.
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, in order for the code to work, you need to make some changes, for example using 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()