Python Requests 库重定向新 URL
- 2024-12-27 08:47:00
- admin 原创
- 114
问题描述:
我一直在浏览 Python 请求文档,但我看不到我想要实现的任何功能。
在我的脚本中我正在设置allow_redirects=True
。
我想知道该页面是否已重定向至其他页面,新的 URL 是什么。
例如,如果起始 URL 为:www.google.com/redirect
最终的 URL 是www.google.co.uk/redirected
我如何获取该 URL?
解决方案 1:
您正在寻找请求历史记录。
属性response.history
是导致最终 URL 的响应列表,可以在 中找到response.url
。
response = requests.get(someurl)
if response.history:
print("Request was redirected")
for resp in response.history:
print(resp.status_code, resp.url)
print("Final destination:")
print(response.status_code, response.url)
else:
print("Request was not redirected")
演示:
>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
... print(resp.status_code, resp.url)
...
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get
解决方案 2:
这是在回答一个稍微不同的问题,但由于我自己也遇到了这个问题,所以我希望它可能对其他人有用。
如果您想使用allow_redirects=False
并直接获取第一个重定向对象,而不是遵循它们的链,并且您只想直接从 302 响应对象中获取重定向位置,那么r.url
将不起作用。相反,它是“Location”标头:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
解决方案 3:
我认为在处理 URL 重定向时调用requests.head
而不是会更安全。在此处requests.get
查看 GitHub 问题:
r = requests.head(url, allow_redirects=True)
print(r.url)
解决方案 4:
该文档有这样的简介https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
解决方案 5:
对于python3.5,可以使用以下代码:
import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)
解决方案 6:
我编写了以下函数来从短 URL(bit.ly、t.co 等)获取完整 URL。
import requests
def expand_short_url(url):
r = requests.head(url, allow_redirects=False)
r.raise_for_status()
if 300 < r.status_code < 400:
url = r.headers.get('Location', url)
return url
使用方法(短网址是该问题的网址):
short_url = 'https://tinyurl.com/' + '4d4ytpbx'
full_url = expand_short_url(short_url)
print(full_url)
输出:
https://stackoverflow.com/questions/20475552/python-requests-library-redirect-new-url
解决方案 7:
所有答案都适用于最终 URL 存在/工作正常的情况。如果最终 URL 似乎不起作用,则以下是捕获所有重定向的方法。有一种情况是最终 URL 不再起作用,而 URL 历史记录等其他方法会出错。
代码片段
long_url = ''
url = 'http://example.com/bla-bla'
try:
while True:
long_url = requests.head(url).headers['location']
print(long_url)
url = long_url
except:
print(long_url)
解决方案 8:
我无法使用请求库,因此不得不采用其他方法。以下是我作为此帖子的解决方案发布的代码。(使用请求获取重定向 URL)
这样,您实际上打开了浏览器,等待浏览器将 URL 记录到历史记录中,然后读取历史记录中的最后一个 URL。我为 Google Chrom 编写了此代码,但如果您使用其他浏览器,您应该能够跟进。
import webbrowser
import sqlite3
import pandas as pd
import shutil
webbrowser.open("https://twitter.com/i/user/2274951674")
#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://twitter.com/ozanbayram01