Reputation: 1383
I'm create new project
I create two function. First func normally run, but second function not working
First func:
#it's work
def twitter(adress):
reqURL = request.urlopen("https://cdn.api.twitter.com/1/urls/count.json?url=%s" % adress)
encodingData = reqURL.headers.get_content_charset()
jsonLoad = json.loads(reqURL.read().decode(encodingData))
print("Sharing:", jsonLoad['count'])
Second func:
#Doesn't work
def facebook(adress):
reqURL = request.urlopen("https://api.facebook.com/method/links.getStats?urls=%s&format=json" % adress)
encodingData = reqURL.headers.get_content_charset()
jsonLoad = json.loads(reqURL.read().decode(encodingData))
print("Sharing:", jsonLoad['share_count'])
How to fix second func(facebook)
I get the error for facebook func:
Traceback (most recent call last):
File "/myproject/main.py", line 24, in <module>
facebook(url)
File "/myproject/main.py", line 15, in facebook
jsonLoad = json.loads(reqURL.read().decode(encodingData))
TypeError: decode() argument 1 must be str, not None
twitter func out:
Sharing: 951
How can I solve this problem?
Thanks
Upvotes: 1
Views: 10007
Reputation: 1122172
The Facebook response doesn't include a charset
parameter indicating the encoding used:
>>> from urllib import request
>>> adress = 'www.zopatista.com'
>>> reqURL = request.urlopen("https://cdn.api.twitter.com/1/urls/count.json?url=%s" % adress)
>>> reqURL.info().get('content-type')
'application/json;charset=utf-8'
>>> reqURL = request.urlopen("https://api.facebook.com/method/links.getStats?urls=%s&format=json" % adress)
>>> reqURL.info().get('content-type')
'application/json'
Note the charset=utf-8
part in the Twitter response.
The JSON standard states that the default characterset is UTF-8, so pass that to the get_content_charset()
method:
encodingData = reqURL.headers.get_content_charset('utf8')
jsonLoad = json.loads(reqURL.read().decode(encodingData))
Now, when no content charset
parameter is set, the default 'utf8'
is returned instead.
Note that Facebook's JSON response contains a list of matches; because you are passing in just one URL, you could take just the first result:
print("Sharing:", jsonLoad[0]['share_count'])
Upvotes: 1