2017-04-22 3 views
-3

스크립트를 작성하려고하는데 그 중 일부는 URL을 사용할 수 있는지 확인해야합니다. 문제는 내가 200,404 등의 답장을 받았을 때 프로그램이 제대로 작동하고 회신을 처리 할 수 ​​있지만 URL에 연결할 수 없을 때 프로그램이 아래 오류로 진행된다는 것입니다. 이 코드의 일부입니다response = URL에 연결할 수없는 경우 requests.get 오류가 발생합니다.

response = requests.get(url) 
print (response) 

오류 :

Traceback (most recent call last): 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 141, in _new_conn 
    (self.host, self.port), self.timeout, **extra_kw) 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\util\connection.py", line 60, in create_connection 
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): 
    File "C:\Python\lib\socket.py", line 743, in getaddrinfo 
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags): 
socket.gaierror: [Errno 11001] getaddrinfo failed 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 600, in urlopen 
    chunked=chunked) 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 345, in _make_request 
    self._validate_conn(conn) 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 844, in _validate_conn 
    conn.connect() 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 284, in connect 
    conn = self._new_conn() 
    File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 150, in _new_conn 
    self, "Failed to establish a new connection: %s" % e) 
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03EC9970>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed 

해결이에 있습니까? URL을 사용할 수 없거나 존재하지 않는 라인을 인쇄하도록 스크립트를 설정할 수 있다면 좋을 것입니다.

+1

그래서 단지 [예외를 catch] (HTTPS :/존재하지 않는 호스트 이름으로

try: response = requests.get(url) except requests.ConnectionError: print("Can't connect to the site, sorry") else: print(response) 

빠른 데모 다음 requests 문서의 Errors and Exceptions section 당신이 여기 requests.ConnectionError exception를 잡을 수있을 것입니다 나타냅니다 /docs.python.org/3/tutorial/errors.html#handling-exceptions)? [* 오류 및 예외 * 섹션] (http://docs.python-requests.org/ko/master/user/quickstart/#errors-and-exceptions)을 참조하십시오. 당신은 이것을 아직 시도 했습니까? 어떤 예외를 잡을 지 문제가 있습니까? –

+1

예외를 포착하고 처리하는 것을 고려 했습니까? – mhawke

답변

1

그냥 catch the exception.

>>> import requests 
>>> try: 
...  response = requests.get("http://no_such_site_exists.imsure") 
... except requests.ConnectionError: 
...  print("Can't connect to the site, sorry") 
... else: 
...  print(response) 
... 
Can't connect to the site, sorry 
관련 문제