如here所示,可以为requests.Session()
设置max-retries
,但我只需要head.status_code
来检查url是否有效和活动
有没有办法在坐骑过程中得到头部
import requests
def valid_active_url(url):
try:
site_ping = requests.head(url, allow_redirects=True)
except requests.exceptions.ConnectionError:
print('Error trying to connect to {}.'.format(url))
try:
if (site_ping.status_code < 400):
return True
else:
return False
except Exception:
return False
return False
基于docs我想我需要:
就我尝试的第一种方法而言:
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=3)
s.mount('http://redirected-domain.com', a)
resp = s.get('http://www.redirected-domain.org')
resp.status_code
我们只是用s.mount()
进入并设置max_retries
吗?似乎是一个冗余,除了http连接将预先建立
同时resp.status_code
返回200
,我期望301
(这就是requests.head
返回的内容)
注意:resp.ok
可能是我在这里所需要的全部
仅仅两个小时的时间,答案就花了五分钟:
基于this answer,看起来
head
请求的资源密集度略低于get,特别是在url包含大量数据的情况下requests.adapters.HTTPAdapter是urllib3库的内置适配器,它是请求库的基础
另一方面,我不确定我在这里检查的正确术语或短语是什么。如果url返回错误代码,它仍然可以是有效的
相关问题 更多 >
编程相关推荐