问题描述
我正在尝试为 Spotify 执行授权代码流程,我使用 Bottle 打开本地主机,然后转到授权页面,之后我被定向到 URL 中带有 access_token 的页面。我如何使用 Bottle(或任何其他库)来获取该 url(它是在起始 localhost 页面之后的第 3 个页面加载以及授予 Spotify 作为用户页面的权限)。
我尝试使用 Selenium,但是当它自动让浏览器打开 localhost 页面时,它不会加载,我什至没有看到 Bottle 正在监听端口。
在运行打开 selenium 的函数之前,我什至尝试使用睡眠,但没有成功
我的代码如下:
from urllib.parse import urlencode
from spotipy import oauth2
from bottle import route,run,request
from selenium import webdriver
import time
import urllib
client_id = ''
client_secret = ''
port_number = 8080
redirect_uri = 'http://localhost:8080/callback'
scope = 'user-read-recently-played'
method = 'GET'
# getting the token following the Authorization code flow - the user will grant permission for the app to use their data.
def get_lookup_url():
auth_url = 'https://accounts.spotify.com/authorize'
auth_data = {
'client_id': f'{client_id}','response_type': 'code','redirect_uri': f'{redirect_uri}','scope': f'{scope}'
}
encoded_auth_data = urlencode(auth_data)
lookup_url = f'{auth_url}?{encoded_auth_data}'
# r = requests.get(lookup_url)
return lookup_url
# print(lookup_url)
# print(r.status_code)
# print(r.text)
# helper function to get the access toekn from the url
def get_access_token_from_url():
driver = webdriver.Chrome('/Users/****/****/chromedriver')
driver.get(redirect_uri)
driver.implicitly_wait(10) # seconds - enough time for me to login to spotify and click the agree button
# urllib.request.urlopen(redirect_uri)
access_token_split = ''
current_url = ''
# current_url = driver.current_url
print(current_url) # TODO remove this line later
if 'access_token' in current_url:
split = current_url.split('#')
print(split[1]) # getting what's after the '#'
split_again = split[1].split('&')
print(split_again) # TODO remove this line later
for i in split_again:
if 'access_token' in i:
access_token_split = i.split('=')
print(access_token_split) # TODO remove this line later
return access_token_split[1]
# login button goes to the lookup url
@route('/callback')
def html_login_button():
auth_url = get_lookup_url() # assigning the function to a variable
htmlLoginButton = "<a id='login' href='" + auth_url + "'>Login to Spotify</a>"
return htmlLoginButton
# time.sleep(10)
# looking for the access_token in the url
get_access_token_from_url()
run(host='',port=port_number,debug=True) # opens at http://localhost:8080/callback```
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)