存在しないURLをrequests.getで取得しようとしてエラー
問題:存在しないURLをrequests.getするとエラー
指定のページ内のソースからリンク先をピックアップして、
リダイレクト先をチェックしようとすると、謎エラーが発生。
エラー内容
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x00000241E7A1D240>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='y!', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000241E7A1D240>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='y!', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000241E7A1D240>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
などなど盛りだくさん。
どうやら
みたいな変なURLに引っかかっているらしい。
というわけでテストする。
url = 'https://Y!'
res =requests.get(url)
で同じ感じのエラーになる。
解決策:try~exceptで無視する
status_codeで判別しようとしたけど、それもエラー。
他の対処方法を調べたけどよくわからないので、この手のエラーは無視して先に進むようにしよう。
闇に葬るようで気持ちが悪いけど根本的な解決策みたいなのがわからないのだ。
無視するということで調べると、try ~ exceptというのが使えそう。
url = 'https://Y!'
try :
res = requests.get(url)
except:
print('ng')
else:
print('hoka')
こんな感じにすればいけた。