2016-04-20 30 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。