使用Python获取重定向的ULR以获取访问代码



这个问题已经被问了好几次,但没有找到任何适合我的答案。我使用请求库来获取重定向url,但我的代码返回了原始url。如果我点击链接,需要几秒钟的时间才能获得重定向url,然后手动提取代码,但我需要通过python获得这些信息。这是我的密码。我尝试过response.history,但它返回空列表。

import requests
response = requests.get("https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize?client_id={client_id}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=user.read%20chat.read&state=12345")
print(response)
print('-------------------')
print(response.url)

我正试图通过以下Microsoft文档来获取代码";https://learn.microsoft.com/en-us/graph/auth-v2-user"。以下是我在stackoverflow中发现的链接,这些链接没有解决我的问题。要通过请求获得重定向URL,如何使用Python获得重定向URL代码?(这可能非常接近我的情况(,如何使用python请求和这个python请求库重定向新的url 来获得重定向url

我没有任何运气通过使用前几篇文章中提到的请求获得重定向url。但我能够使用网络浏览器库解决这个问题,然后使用sqlite 3获取浏览器历史记录,并能够获得我想要的结果。为了使用Graph API,我不得不通过邮递员并将邮递员url添加到我的应用程序注册中,但如果你只是想获得重定向url,你可以遵循相同的代码,你应该获得重定向url。

如果有更好的解决方案,请告诉我。

这是我的代码:

import webbrowser
import sqlite3
import pandas as pd
import shutil
webbrowser.open("https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize?client_id={client_id}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=user.read%20chat.read&state=12345")
#source file is where the history of your webbroser is saved, I was using chrome, but it should be the same process if you are using different browser
source_file = 'C:\Users\{your_user_id}\AppData\Local\Google\Chrome\User Data\Default\History'
# could not directly connect to history file as it was locked and had to make a copy of it in different location
destination_file = 'C:\Users\{user}\Downloads\History'
time.sleep(30) # there is some delay to update the history file, so 30 sec wait give it enough time to make sure your last url get logged
shutil.copy(source_file,destination_file) # copying the file.
con = sqlite3.connect('C:\Users\{user}\Downloads\History')#connecting to browser history
cursor = con.execute("SELECT * FROM urls")
names = [description[0] for description in cursor.description]
urls = cursor.fetchall()
con.close()
df_history = pd.DataFrame(urls,columns=names)
last_url = df_history.loc[len(df_history)-1,'url']
print(last_url)
>>https://oauth.pstmn.io/v1/browser-callback?code={code}&state=12345&session_state={session_state}#

最新更新