检测过期短链接遇阻:requests库返回状态码与响应URL异常
解决短链接过期跳转的requests处理方案
不用必须用Selenium,你可以通过以下几种方式用requests获取到浏览器里的目标跳转URL:
- 模拟浏览器请求头
很多短链接服务会检查请求的User-Agent等头信息,判断请求是否来自真实浏览器。给requests添加浏览器风格的请求头后,可能会触发正确的跳转逻辑:
import requests # 模拟Chrome浏览器的请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # 允许自动跟随重定向 response = requests.get('https://short.ly/abcdef', headers=headers, allow_redirects=True) # 打印最终跳转后的URL print(response.url)
- 解析页面中的JavaScript跳转
如果短链接的过期跳转是通过前端JavaScript实现的(比如window.location.href),可以直接解析返回的HTML内容,提取跳转目标:
import re import requests from urllib.parse import urlparse, parse_qs headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0 Safari/537.36'} response = requests.get('https://short.ly/abcdef', headers=headers) # 匹配常见的JS跳转语句 jump_regex = re.compile(r'window\.location\.href\s*=\s*["\'](.*?)["\']') match_result = jump_regex.search(response.text) if match_result: target_url = match_result.group(1) print(f"提取到跳转URL: {target_url}") # 解析URL参数判断是否过期 parsed_url = urlparse(target_url) params = parse_qs(parsed_url.query) if 'ref' in params and params['ref'][0] == 'expired': print("该短链接已过期")
- 检查Meta Refresh跳转
部分网站会用<meta>标签实现页面跳转,这种情况可以用HTML解析库提取跳转目标:
from bs4 import BeautifulSoup import requests from urllib.parse import urlparse, parse_qs headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0 Safari/537.36'} response = requests.get('https://short.ly/abcdef', headers=headers) soup = BeautifulSoup(response.text, 'html.parser') meta_refresh_tag = soup.find('meta', attrs={'http-equiv': 'refresh'}) if meta_refresh_tag: content_str = meta_refresh_tag.get('content') if 'url=' in content_str: target_url = content_str.split('url=')[1] print(f"Meta跳转目标URL: {target_url}") # 解析参数判断过期状态 parsed_params = parse_qs(urlparse(target_url).query) if parsed_params.get('ref') == ['expired']: print("短链接已过期")
只有当短链接的跳转依赖极其复杂的JavaScript渲染(比如需要执行多步JS逻辑、依赖登录态或浏览器环境API)时,才需要考虑使用Selenium,否则上述方法足够满足需求。
内容的提问来源于stack exchange,提问作者MartinV
相关产品推荐
相关产品推荐

