网络编程
位置:首页>> 网络编程>> Python编程>> python 重定向获取真实url的方法

python 重定向获取真实url的方法

作者:野沐沐  发布时间:2022-10-25 03:24:46 

标签:python,url,重定向

楼主在做公司项目的时候遇到url重定向的问题,因此上网简单查找,作出如下结果

由于使用的是语言是python所以以下是python的简单解决方案


http_headers = { 'Accept': '*/*','Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'}

def get_real_url(url):
rs = requests.get(url,headers=http_headers,timeout=10)
rs.url

以上代码未有重试机制,下面加上重试机制加以完善


def get_real_url(url,try_count = 1):
if try_count > 3:
return url
try:
rs = requests.get(url,headers=http_headers,timeout=10)
if rs.status_code > 400:
return get_real_url(url,try_count+1)
return rs.url
except:
return get_real_url(url, try_count + 1)

来源:https://blog.csdn.net/yanxiaobo1991/article/details/75529581

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com