Python请求异常

时间:2017-08-04 10:21:27

标签: python exception-handling python-requests

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


    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"
 

6 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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")

答案 2 :(得分:0)

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

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

如果你不理解这些差异,你应该尝试更好地理解你在学习Python的书/文档/课程中如何运作。

答案 3 :(得分:0)

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

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

答案 4 :(得分: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")

答案 5 :(得分:0)

如我所见,向您抛出的异常是一个newConnectionError,首先捕获该异常(以便更好地处理异常)

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

用于更好地处理异常的代码:

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: