python - Python:如何使用瓶子从本地主机获取某个 url?
问题描述
我正在尝试为 Spotify 执行授权代码流,我使用瓶子打开本地主机,然后转到授权页面,之后我被定向到 URL 中带有 access_token 的页面。如何使用瓶子(或任何其他库)来获取该 url(它是在启动 localhost 页面和授予 Spotify 作为用户页面之后的第三个页面加载)。
我尝试使用 Selenium,但是当它自动打开浏览器以打开 localhost 页面时,它不会加载,我什至没有看到瓶子在监听端口。
我什至尝试在运行打开硒的功能之前应用睡眠,但它没有成功
我的代码如下:
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```
解决方案
推荐阅读
- python - 使用 Django REST API python 的 Ajax 调用?
- sql - 如何在 bigquery 中移动年周字段
- c# - Json.net 仅序列化某些属性
- google-bigquery - BigQuery python 客户端库在 insert_rows 上删除数据
- ios - Swift iOS - 如何为 CollectionView 的第二部分查找 CGPoint x/y 值
- ios - iOS推送通知自定义声音无法弄清楚
- php - 带有 XPath 的 PHP 不返回托管主机 bplaced 的结果
- python - 无法使用 FFT 重新创建相同的声音
- python - 如何在 Python 和 beautifulsoup 中从 CDATA 中提取数据?
- angular - Angular 2 Input ngFor 不只更新 1 个输入值