首页 > 解决方案 > 如何使用请求模块跳过连接超时 url

问题描述

嗨,我如何使用请求模块来处理一堆 URL,如果列表中的 URL 需要更多时间来加载或连接超时,我如何跳过该特定 URL 并跳到下一个

def req():
with open('demofile.txt','r') as http:
    for url in http.readlines():
        req = url.strip()
        print(req)
        page=requests.get("http://"+req,verify=False)
        if page.status_code == 400:
            break
        else:
            continue
        time.sleep(1)

标签: pythonpython-3.xpython-requests

解决方案


如果超时,您可以引发异常并继续finally阻止下一个请求,

import requests
import logging

timeout = 0.00001

try:
    response = requests.get(url="https://google.com", timeout=timeout)
except requests.exceptions.ConnectTimeout as e:
    logging.error("Time out!")
finally:
    # continue request here
    print("hello")


# output,
ERROR:root:Time out!
hello

推荐阅读