如何用Python反转Google AMP API,从AMP URL提取原始URL?
从AMP URL还原原始URL的Python实现方法
嘿,这个需求我刚好折腾过!从AMP URL反转得到原始页面地址其实有两种靠谱的方式,我给你详细拆解,用Python实现起来超简单~
方法一:直接解析AMP页面的规范链接(最通用)
根据AMP的官方规范,每个AMP页面必须包含一个rel="canonical"的链接标签,指向对应的原始页面。我们只需要爬取AMP页面的HTML内容,提取这个标签的href属性就行,完全不需要依赖任何API密钥。
步骤:
- 发送HTTP请求获取AMP页面的HTML内容
- 用HTML解析库定位到
rel="canonical"的<link>标签 - 提取标签中的
href值,就是原始URL
Python代码实现:
首先需要安装依赖库:
pip install requests beautifulsoup4
然后是核心代码:
import requests from bs4 import BeautifulSoup def amp_to_original(amp_url): try: # 模拟浏览器请求,避免被反爬拦截 headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"} response = requests.get(amp_url, headers=headers) response.raise_for_status() # 检查请求是否成功 # 解析HTML内容 soup = BeautifulSoup(response.text, "html.parser") # 查找规范链接标签 canonical_link = soup.find("link", rel="canonical") if canonical_link and canonical_link.get("href"): return canonical_link["href"] else: return "⚠️ 找不到原始URL,可能该AMP页面不符合规范" except requests.exceptions.RequestException as e: return f"❌ 请求出错:{str(e)}" # 测试你的示例URL test_amp_url = "https://amp.cnn.com/cnn/2018/03/08/politics/jeff-flake-anti-tariff-bill/" original_url = amp_to_original(test_amp_url) print(f"原始URL:{original_url}")
运行这段代码,就能得到你想要的结果:https://cnn.com/2018/03/08/politics/jeff-flake-anti-tariff-bill/
方法二:使用Google AMP转换API(官方方案)
如果你想依赖官方API来做转换,可以用Google的AMP转换服务,但需要先在Google Cloud控制台启用AMP转换API并获取API密钥(有免费调用额度,但超过需要付费)。
Python代码实现:
import requests def amp_to_original_via_api(amp_url, api_key): api_endpoint = f"https://amp.googleapis.com/v1/convert?url={amp_url}&key={api_key}" try: response = requests.get(api_endpoint) response.raise_for_status() result = response.json() return result.get("canonicalUrl", "⚠️ API返回中未找到原始URL") except requests.exceptions.RequestException as e: return f"❌ API请求出错:{str(e)}" # 使用示例(替换成你的API密钥) # api_key = "YOUR_GOOGLE_CLOUD_API_KEY" # original_url = amp_to_original_via_api(test_amp_url, api_key) # print(original_url)
一些注意事项
- 优先用方法一:不需要API密钥,无调用限制,而且是AMP规范要求的标准方式,兼容性最好
- 避免硬改URL结构:比如直接去掉
amp.前缀,这种方法只适用于部分网站,很多网站的AMP URL结构不一样(比如m.example.com/amp/article),很容易出错 - 反爬处理:如果遇到请求被拦截,可以调整
User-Agent,或者添加代理、延迟请求等策略
内容的提问来源于stack exchange,提问作者Markyroson
相关产品推荐
相关产品推荐

