2014-10-19 40 views
1

我嘗試編寫一個簡單的python3腳本,通過youtube API獲取一些播放列表信息。然而,我總是得到一個401錯誤,而當我在瀏覽器中輸入請求字符串或使用w-get發出請求時,它完美工作。我相對較新的python,我想我在這裏錯過了一些重要的一點。當使用python查詢YouTube播放列表時,「HTTP錯誤401:未經授權」

這是我的腳本。當然,我實際上使用了一個真正的API密鑰。

from urllib.request import Request, urlopen 
from urllib.parse import urlencode 


api_key = "myApiKey" 

playlist_id = input('Enter playlist id: ') 
output_file = input('Enter name of output file (default is playlist id') 

if output_file == '': 
    output_file = playlist_id 

url = 'https://www.googleapis.com/youtube/v3/playlistItems' 

params = {'part': 'snippet', 
      'playlistId': playlist_id, 
      'key': api_key, 
      'fields': 'items/snippet(title,description,position,resourceId/videoId),nextPageToken,pageInfo/totalResults', 
      'maxResults': 50, 
      'pageToken': '', } 

data = urlencode(params) 

request = Request(url, data.encode('utf-8')) 
response = urlopen(request) 
content = response.read() 

print(content) 

不幸的是它上升一個錯誤在response = urlopen(request)

Traceback (most recent call last): 
File "gpd-helper.py", line 35, in <module> 
    response = urlopen(request) 
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen 
    return opener.open(url, data, timeout) 
File "/usr/lib/python3.4/urllib/request.py", line 461, in open 
    response = meth(req, response) 
File "/usr/lib/python3.4/urllib/request.py", line 571, in http_response 
    'http', request, response, code, msg, hdrs) 
File "/usr/lib/python3.4/urllib/request.py", line 499, in error 
    return self._call_chain(*args) 
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain 
    result = func(*args) 
File "/usr/lib/python3.4/urllib/request.py", line 579, in http_error_default 
    raise HTTPError(req.full_url, code, msg, hdrs, fp) 
urllib.error.HTTPError: HTTP Error 401: Unauthorized 

我擡起頭來的文件,但無法找到任何暗示。根據文檔,列出公共播放列表不需要api鍵以外的其他身份驗證。

回答

1

在深入瞭解python和google文檔後,我找到了解決我的問題的方法。

Request object automatically creates a POST request被賦予數據參數時但youtube api expects GET(帶有post數據)

的解決方案是醚供給GET參數的方法參數在python 3.4

request = Request(url, data.encode('utf-8'), method='GET') 

或連接的帶urlencoded後數據的網址

request = Request(url + '?' + data) 
相關問題