python-3.x - Python3 的 try/except 在使用 requests 库时不起作用
问题描述
我用库写了一个简单的程序requests
,我想打印'对不起,url不存在!' 如果输入网址错误。我发现如果我输入一个假的 url 来
get_request()
运行,它会给我一个ConnectionError
错误,所以我把它放在后面except
:
import requests
def get_request(url):
a = requests.get(url)
return a
myurl = 'https://nberccc.com/videos?page=1' # a fake website url
try:
c = get_request(myurl)
except ConnectionError:
print('sorry, the url does not exist!')
它返回:
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py in _new_conn(self)
158 conn = connection.create_connection(
--> 159 (self._dns_host, self.port), self.timeout, **extra_kw)
160
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options)
56
---> 57 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
58 af, socktype, proto, canonname, sa = res
C:\ProgramData\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
747 addrlist = []
--> 748 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
749 af, socktype, proto, canonname, sa = res
gaierror: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
NewConnectionError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
342 try:
--> 343 self._validate_conn(conn)
344 except (SocketTimeout, BaseSSLError) as e:
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
838 if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
--> 839 conn.connect()
840
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py in connect(self)
300 # Add certificate verification
--> 301 conn = self._new_conn()
302 hostname = self.host
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py in _new_conn(self)
167 raise NewConnectionError(
--> 168 self, "Failed to establish a new connection: %s" % e)
169
NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x000001602C18F4E0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
MaxRetryError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
448 retries=self.max_retries,
--> 449 timeout=timeout
450 )
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
637 retries = retries.increment(method, url, error=e, _pool=self,
--> 638 _stacktrace=sys.exc_info()[2])
639 retries.sleep()
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
397 if new_retry.is_exhausted():
--> 398 raise MaxRetryError(_pool, url, error or ResponseError(cause))
399
MaxRetryError: HTTPSConnectionPool(host='porndoe111.com', port=443): Max retries exceeded with url: /videos?page=1 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000001602C18F4E0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
During handling of the above exception, another exception occurred:
ConnectionError Traceback (most recent call last)
<ipython-input-37-f61b8d93ce3e> in <module>
1 myurl = 'https://nberccc.com/videos?page=1'
----> 2 requests.get(url)
3
4 def get_request(url):
5 a = requests.get(url)
C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py in get(url, params, **kwargs)
73
74 kwargs.setdefault('allow_redirects', True)
---> 75 return request('get', url, params=params, **kwargs)
76
77
C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
58 # cases, and look like a memory leak in others.
59 with sessions.Session() as session:
---> 60 return session.request(method=method, url=url, **kwargs)
61
62
C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
531 }
532 send_kwargs.update(settings)
--> 533 resp = self.send(prep, **send_kwargs)
534
535 return resp
C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
644
645 # Send the request
--> 646 r = adapter.send(request, **kwargs)
647
648 # Total elapsed time of the request (approximately)
C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
514 raise SSLError(e, request=request)
515
--> 516 raise ConnectionError(e, request=request)
517
518 except ClosedPoolError as e:
ConnectionError: HTTPSConnectionPool(host='porndoe111.com', port=443): Max retries exceeded with url: /videos?page=1 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000001602C18F4E0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
为什么它不打印我自己的错误消息?
当我运行这个:
myurl1 = 'https://github.com/songxxiao' # a normal website url
try:
c = get_request(myurl1)
except ConnectionError:
print('sorry, the url does not exist!')
它运作良好。
那么如何修改我上面的代码以捕获该错误并打印我自己的错误消息?
解决方案
推荐阅读
- python - 如何完全离线使用arabert-v2?
- protocol-buffers - protobuf 中是否有替代 flatbuffers 结构的方法?
- fragment - 使用TDengine时如何避免更新操作时产生碎片数据?
- css - 选择一系列嵌套元素中的第二个元素(每个元素只有一个子元素)
- amazon-web-services - AWS Cloudformation Lambda 和事件规则 - Lambda 没有被带后缀的 s3 事件触发?
- matlab - 使用 MATLAB 数值求解 PDE
- c++ - 使基类受保护成员成为pybind11中的只读参数
- r - 如何在不越过日期变更线的情况下找到恒向线距离?
- javascript - 加载多条记录时,如何防止 TailwindCSS 表扩展?
- terraform - 将大型手动管理的 AWS 账户迁移到 Terraform 配置中