我的要求几乎与Requests — how to tell if you're getting a success message?相同
但当我无法到达URL..Here时,我需要打印错误,这是我的尝试。
# setting up the URL and checking the conection by printing the status
url = 'https://www.google.lk'
try:
page = requests.get(url)
print(page.status_code)
except requests.exceptions.HTTPError as err:
print("Error")问题不是只打印“错误”,而是打印一个完整的错误信息,如下所示。
Traceback (most recent call last):
File "testrun.py", line 22, in <module>
page = requests.get(url)
File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/root/anaconda3/envs/py36/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='learn.microsoft.com', port=443): Max retries exceeded with url: /en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7ff91a543198>: Failed to establish a new connection: [Errno 110] Connection timed out',))有人能告诉我,只有在有任何问题的时候,我才应该修改我的代码来打印“错误”吗?然后我可以把它扩展到其他要求。
发布于 2022-09-26 10:04:43
你没有捕捉到正确的异常。
import requests
url = 'https://www.googlggggggge.lk'
try:
page = requests.get(url)
print(page.status_code)
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):
print("Error")您也可以执行except Exception,但是请注意,Exception太宽,在大多数情况下不推荐使用,因为它会捕获所有错误。
发布于 2022-09-26 10:03:35
您需要使用通用异常except或捕获请求模块可能抛出的所有异常,例如except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError)。
有关完整列表,请参见:Correct way to try/except using Python requests module?
https://stackoverflow.com/questions/73852472
复制相似问题