【发布时间】:2019-03-05 10:52:03
【问题描述】:
我一直在尝试研究如何通过 API 下载 YouTube 字幕,但官方说明是针对命令行代码量身定制的,而我正在尝试在 Python Shell 中执行此操作。
目前我一直关注此页面无济于事 - https://developers.google.com/youtube/v3/docs/captions/list
似乎让我感到困惑的是与存储和 args 相关的代码片段,即使经过多次谷歌搜索对我来说也没有任何意义。
见下面的存储代码:
storage = Storage("%s-oauth2.json" % sys.argv[0])
#nowhere on the page does it refer to this oauth2.json file
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
#if credentials is none why would storage still be needed as an argument?
在页面的后半部分,都是向 args.parser 添加参数,这似乎是我在 Python Shell 中工作时不想使用的命令行内容。
我也一直在阅读有关为 YouTube API 获得授权 OAuth 2.0 的官方页面,因此我可以自己重写此代码,但我无法通过这部分:https://developers.google.com/api-client-library/python/auth/web-app
第 5 步:交换刷新和访问令牌的授权码 Web 服务器收到授权码后,可以将授权码换成访问令牌。 在您的回调页面上,使用 google-authlibrary 验证授权服务器响应。然后,使用 flow.fetch_token 方法将该响应中的授权代码交换为访问令牌:
state = flask.session['state']
这是我从上面的代码语句中得到的错误:
RuntimeError:在请求上下文之外工作。 这通常意味着您尝试使用需要的功能 一个活动的 HTTP 请求。请参阅有关测试的文档 有关如何避免此问题的信息。
主要是通过对 Oauth 2.0 流程的大量挖掘,我认为我无法获取 flow.fetch_token 以将我的授权代码交换为访问令牌。
我已经测试了我所有的凭据,所以它们都很好,它正在获得授权,我正在努力解决。
到目前为止,这是我在第一个链接上作为 Captions API 代码的简化版本编写的代码:
import google.oauth2.credentials
import google_auth_oauthlib.flow
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file("//client_secret_file.json", scopes=["https://www.googleapis.com/auth/youtube.force-ssl"])
flow.redirect_uri = "http://localhost:8080"
authorization_url, state = flow.authorization_url(access_type="offline", include_granted_scopes="true")
flask.redirect(authorization_url)
[响应 929 字节 [302 FOUND]]
state = flask.session['state']
[运行时错误]
总结:
如何从 Python Shell 中的代码下载 YouTube 字幕?我已经设置了我的凭据,只是无法让 Web 服务器给我访问令牌,所以我可以执行其余的代码。我会使用 captions.list 链接上的代码,但我无法通过为命令行编写的存储代码语句和 args.arguments。
【问题讨论】:
标签: python python-3.x youtube-api youtube-data-api