使用request_head的max_retries设置获取status_code

问题描述 投票:2回答:1

正如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我想我需要:

  • 看看session.mount方法结果是否返回状态代码(我还没有找到)
  • 滚动我自己的重试方法,可能是像thisthis这样的装饰者,或者像this这样的(不太雄辩的)循环。

就我尝试的第一种方法而言:

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可能是我在这里需要的全部内容。

python python-requests
1个回答
0
投票

经过短短两个小时的研究,答案花了五分钟:

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仍然有效。

© www.soinside.com 2019 - 2024. All rights reserved.