Python请求异常

问题描述 投票:-1回答:6

当我尝试发布请求时收到此错误,我只是尝试添加异常,但异常无法处理它


    raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='www.examplewebsite.com', port=443): Max retries exceeded with url: /login/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

我试过这个

except requests.exceptions.ConnectionError as C:
    print "Failed"
except requests.exceptions.TooManyRedirects:
    print "Failed"

但仍然是相同的错误

有什么方法可以解决吗?

编辑:

def job(lk):
    try:
        session = requests.session()

        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}
        r = session.get("https://www.example.com/login/")
        post = session.post('https://www.example.com', data={"log": "name",
                                                                       "pwd": "name",},
                                                                        headers=headers)
        rGet = session.get('https://www.example.com')


    except requests.exceptions.ConnectionError as C:
        print "Failed 2"
    except requests.exceptions.TooManyRedirects:
        print "Failed 3"
 
python exception-handling python-requests
6个回答
0
投票

你的try / except块不在正确的位置,它必须在函数内:

def job(lk):
    session = requests.session()
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}
    try:

        r = session.get("https://www.example.com/login/")
        post = session.post(
            'https://www.example.com', 
            data={"log": "name", "pwd": "name",},                                                                 
            headers=headers
            )
        rGet = session.get('https://www.example.com')


    except requests.exceptions.ConnectionError as C:
        print "Failed 2"
    except requests.exceptions.TooManyRedirects:
        print "Failed 3"

另请注意,您当前的异常处理对于故障排除不是非常有用 - 您没有确切的异常,完整的回溯,并且您甚至不知道三个请求中的哪一个失败 - 但我认为这只是占位符代码ATM。


0
投票

你的try catch块应该在函数内部。

def job(lk):
    try:
        session = requests.session()

        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}
        r = session.get("https://www.example.com/login/")
        post = session.post('https://www.example.com', data={"log": "name",
                                                                       "pwd": "name",},
                                                                        headers=headers)
        rGet = session.get('https://www.example.com')


    except requests.exceptions.ConnectionError:
        print("Failed 2")
    except requests.exceptions.TooManyRedirects:
        print("Failed 3")

0
投票

正如Bruno所说,try / except应该在函数内部(或者包含调用函数的代码)。

原因是当函数被调用并运行时会发生异常;而你的try / except块只会捕获在声明函数时引发的错误,而不是在它运行时。

如果您不理解这些差异,您应该尝试更好地理解函数在您用于学习Python的书籍/文档/课程中的工作原理。


0
投票

也许你没有得到你认为你得到的例外。使用通用except运行代码以确定引发的异常类型:

except Exception as exc:
    print(type(exc), str(exc))

0
投票

你可以使用这样的东西 -

try:
    res = requests.get(adress,timeout=30)
except requests.ConnectionError as e:
    print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")
    print(str(e))            
except requests.Timeout as e:
    print("OOPS!! Timeout Error")
    print(str(e))
except requests.RequestException as e:
    print("OOPS!! General Error")
    print(str(e))
except KeyboardInterrupt:
    print("Someone closed the program")

0
投票

正如我所看到的,抛出的异常是newConnectionError,首先捕获这个(为了更好的异常处理)

第二,在例外它告诉你它超过了url的最大重试次数,用户名,密码是否正确?,并且是你试图连接到“log”的服务器的参数:“name”“pwd”:“name “

更好的异常处理代码:

def job(lk):
    try:
        session = requests.session()

        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'}
        r = session.get("https://www.example.com/login/")
        post = session.post('https://www.example.com', data={"log": "name",
                                                                   "pwd": "name",},
                                                                    headers=headers)
        rGet = session.get('https://www.example.com')

    except NewConnectionError as nCE:
        print f"failed 1 - NewConnection error: {nCE}"

    except requests.exceptions.ConnectionError as C:
        print "Failed 2"

    except requests.exceptions.TooManyRedirects:
        print "Failed 3"except NewConnectionError:
© www.soinside.com 2019 - 2024. All rights reserved.