You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取URL跳转后的最终地址?requests库未返回正确重定向URL如何解决

解决方法

根本原因

你使用的allow_redirects参数仅能处理服务端返回3xx状态码的HTTP原生重定向,该页面的跳转是通过前端<meta>标签实现的页面级跳转,不属于HTTP重定向范畴,因此requests无法直接捕获跳转后的地址。

方案1:轻量化解析提取(无浏览器依赖,性能高)

这个站点的跳转规则固定,直接解析页面内的跳转标签即可拿到PDF地址,所需依赖及代码如下:
首先安装依赖:

pip install requests beautifulsoup4

运行代码:

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import re

origin_url = "https://trade.ec.europa.eu/doclib/html/153814.htm"
resp = requests.get(origin_url)
soup = BeautifulSoup(resp.text, "html.parser")

# 定位跳转用的meta标签
refresh_tag = soup.find("meta", {"http-equiv": re.compile("Refresh", re.IGNORECASE)})
if refresh_tag:
    # 提取跳转路径拼接为完整URL
    redirect_path = refresh_tag["content"].split("url=")[-1]
    final_pdf_url = urljoin(origin_url, redirect_path)
    print(final_pdf_url)

运行后直接输出目标PDF地址:https://trade.ec.europa.eu/doclib/docs/2015/september/tradoc_153814.pdf

方案2:模拟浏览器适配所有前端跳转场景

如果遇到跳转逻辑更复杂(如JS动态生成跳转地址)的场景,可以用Selenium模拟浏览器运行自动触发跳转后获取地址:
安装依赖:

pip install selenium webdriver-manager

运行代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://trade.ec.europa.eu/doclib/html/153814.htm")
time.sleep(1) # 等待跳转完成
final_pdf_url = driver.current_url
print(final_pdf_url)
driver.quit()

内容的提问来源于stack exchange,提问作者piñatabreaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 14:36:07