正如here所见,max-retries
可以设置为requests.Session()
,但我只需要head.status_code
来检查网址是否有效且有效。
有没有办法在挂载会话中获得头部?
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连接。
此外qazxsw poi返回qazxsw poi,我期待一个qazxsw poi(这是resp.status_code
回归。
注意:200
可能是我在这里需要的全部内容。
经过短短两个小时的研究,答案花了五分钟:
301
基于requests.head
,看起来resp.ok
请求的资源密集程度略低于get,特别是如果url包含大量数据。
def valid_url(url):
if (url.lower() == 'none') or (url == ''):
return False
try:
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=5)
s.mount(url, a)
resp = s.head(url)
return resp.ok
except requests.exceptions.MissingSchema:
# If it's missing the schema, run again with schema added
return valid_url('http://' + url)
except requests.exceptions.ConnectionError:
print('Error trying to connect to {}.'.format(url))
return False
是urllib3库的内置适配器,它是Requests库的基础。
另一方面,我不确定我在这里检查的正确术语或短语是什么。如果URL返回错误代码,则该URL仍然有效。