2016-04-20 31 views
0

我一直在关注this tutorial从fb下载一些页面信息。从Facebook下载页面文章。我如何处理JSON数据?

我使用Python 3.5,本教程使用python2。

我在开始时遇到了一些HTTP错误代码400,基本上说我必须使用https协议而不是http。所以我现在已经在闲置测试了,数据即将到来,并且像我这样的新手看起来像JSON。但是当我试图把它传递给json.loads它是从使用的urllib库,而不是urllib2的图书馆和https,而不是http我不什么我做错了给这个错误

Traceback (most recent call last): 
    File "C:\Users\Levo\Desktop\facebookscrape.py", line 38, in <module> 
    testFacebookPageData(page_id, access_token) 
    File "C:\Users\Levo\Desktop\facebookscrape.py", line 34, in testFacebookPageData 
    data = json.loads(requests_until_succeed(url)) 
    File "C:\Users\Levo\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 312, in loads 
    s.__class__.__name__)) 
TypeError: the JSON object must be str, not 'bytes' 

除? https的加密问题?

def requests_until_succeed(url): 
    req = urllib.request.Request(url) 
    success = False 
    while success is False: 
     try: 
      response = urllib.request.urlopen(req) 
      if response.getcode() == 200: 
       success = True 
     except Exception as e: 
      print(e) 
      time.sleep(5) 

      print ("Error for URL %s: %s" % (url, datetime.datetime.now())) 

     return response.read() 


def testFacebookPageData(page_id, access_token): 
    base = "https://graph.facebook.com/v2.6" 
    node = "/" + page_id + "/feed" 
    parameters = "/?access_token=%s" % access_token 
    url = base + node + parameters 

    data = json.loads(requests_until_succeed(url)) 

    print(json.dumps(data, indent = 4, sort_keys=True)) 

testFacebookPageData(page_id, access_token) 

回答

0

json.loads接受python3字符串,它是unicode的,responce.read()返回二进制串。

使用data = json.loads(requests_until_succeed(url).decode('utf-8')),因为responce最有可能是utf-8。