【问题标题】:How to use the requests module to skip connection timeout urls如何使用请求模块跳过连接超时 url
【发布时间】:2018-11-04 10:07:58
【问题描述】:

您好,我如何使用请求模块来处理一堆 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)

【问题讨论】:

    标签: python python-3.x python-requests


    【解决方案1】:

    如果超时,您可以引发异常并继续 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
    

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多