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

如何无需打开浏览器,通过代码获取JSON返回的远程URL解析后的实际页面URL?

如何编程获取重定向后的实际URL

浏览器打开该URL时的解析过程,本质是服务器返回了HTTP重定向响应(如301/302状态码),浏览器自动完成了跳转。要在代码中实现这一逻辑,只需要发送HTTP请求并跟踪重定向,即可获取最终的实际页面URL。

以下是几种主流编程语言的实现示例:

Python(使用requests库)

import requests

original_url = "https://somesite.com/mainlink/1eb-68a8-40be-a3-5679e/utilities/927-40-b958-3b5?pagePath=teststaff"

# 发送GET请求,默认自动跟随重定向
response = requests.get(original_url)
# 获取最终跳转后的URL
final_url = response.url

print(final_url)
  • 若需自定义重定向次数,可通过max_redirects参数调整;如果遇到请求被拦截,可添加模拟浏览器的User-Agent请求头。

Node.js(使用axios库)

const axios = require('axios');

const originalUrl = "https://somesite.com/mainlink/1eb-68a8-40be-a3-5679e/utilities/927-40-b958-3b5?pagePath=teststaff";

axios.get(originalUrl, { followRedirects: true })
  .then(response => {
    // 输出最终URL
    console.log(response.request.res.responseUrl);
  })
  .catch(error => {
    console.error('请求失败:', error);
  });

Java(使用HttpURLConnection)

import java.net.HttpURLConnection;
import java.net.URL;

public class RedirectTracker {
    public static void main(String[] args) throws Exception {
        String originalUrl = "https://somesite.com/mainlink/1eb-68a8-40be-a3-5679e/utilities/927-40-b958-3b5?pagePath=teststaff";
        URL url = new URL(originalUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        // 开启自动跟随重定向
        conn.setInstanceFollowRedirects(true);
        // 触发请求(获取响应码即可完成跳转跟踪)
        conn.getResponseCode();
        
        // 获取最终URL
        String finalUrl = conn.getURL().toString();
        System.out.println(finalUrl);
        
        conn.disconnect();
    }
}

特殊情况处理

如果目标URL是通过JavaScript跳转(而非HTTP重定向),则需要使用无头浏览器工具(如Playwright、Pyppeteer)执行页面中的JS代码,才能获取最终跳转URL。这种场景相对少见,多数情况下HTTP重定向跟踪即可解决问题。

内容的提问来源于stack exchange,提问作者Joe_12345

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:25:41