【问题标题】:"HTTP Error 401: Unauthorized" when querying youtube api for playlist with python使用 python 查询 youtube api 以获取播放列表时出现“HTTP 错误 401:未经授权”
【发布时间】:2014-12-14 13:56:30
【问题描述】:

我尝试编写一个简单的 python3 脚本,通过 youtube API 获取一些播放列表信息。但是,我总是收到 401 错误,而当我在浏览器中输入请求字符串或使用 w-get 发出请求时,它可以正常工作。我对 python 比较陌生,我想我在这里遗漏了一些重要的点。

这是我的脚本。当然,我实际上使用的是真正的 API-Key。

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 密钥以外的其他身份验证。

【问题讨论】:

    标签: python python-3.x youtube-api urllib http-error


    【解决方案1】:

    在深入研究了 python 和 google 的文档后,我找到了解决问题的方法。

    Pythons Request object automatically creates a POST request 当数据参数被给出但youtube api expects GET(带有后参数)

    解决方案是在 python 3.4 中为方法参数提供 GET 参数

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

    或将 url 与 urlencoded 发布数据连接起来

    request = Request(url + '?' + data)
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2013-09-13
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多