簡體   English   中英

Python 請求例外

[英]Python Requests Exceptions

當我嘗試發布請求時出現此錯誤,我只是嘗試添加一個異常,但異常無法處理它


    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"
 

你可以使用這樣的東西 -

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")

您的 try/except 塊不在正確的位置,它必須function 內:

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"

另請注意,您當前的異常處理對於故障排除不是很有用——您沒有確切的異常、完整的回溯,並且您甚至不知道三個請求中的哪一個失敗了——但我認為這只是占位符代碼自動櫃員機。

你的try catch塊應該在 function 里面。

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")

正如 Bruno 所說,try/except 應該在 function 內(或環繞調用該函數的代碼)。

原因是function調用運行時出現異常; 而你的 try/except 塊因為它只捕獲在聲明 function時引發的錯誤,而不是在它運行時。

如果您不了解其中的區別,您應該嘗試更好地理解函數在您用來學習 Python 的書籍/文檔/課程中的工作原理。

也許您沒有得到您認為得到的異常。 使用通用except運行代碼以確定引發的異常類型:

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

如我所見,拋給你的異常是一個 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:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM