2

requests.get(invalid_url)無効な URL をリクエストすると、次の例外がスローされることに気付きました。

Traceback (most recent call last):
  File "/usr/lib/python3.4/socket.py", line 530, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 607, in urlopen
    raise MaxRetryError(self, url, e)
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='sparkandshine.me', port=80): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)

During handling of the above exception, another exception occurred:
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 378, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='sparkandshine.me', port=80): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)

これらの例外をキャッチして、ドメイン名が登録されているかどうかを正確に判断できますか? ソースコードは次のとおりです。

#!/usr/bin/env python3
import http
import urllib3
import requests

url = 'http://example.com'
try :
    r = requests.get(url)
except (http.client.HTTPException, urllib3.exceptions.MaxRetryError, requests.exceptions.ConnectionError):
    print(url) #this domain name is not registered?
4

2 に答える 2

4

いいえ; ドメインが登録されていて、ルート ドメイン名の IP アドレスがなくてもまったく問題ありません。ましてや、その IP アドレスのポート 80 でサーバーを実行することはできません。

于 2015-07-21T10:10:22.560 に答える
3

As mentioned by @tripleee, it is not very precise. I find another way to determine if a domain name is registered or not, using the python module pywhois.

To install it,

pip install python-whois

Here is an example.

#!/usr/bin/env python
import whois

url = 'example.com'
try :
    w = whois.whois(url)
except (whois.parser.PywhoisError):
    print(url)

PS: not support for python3.

于 2015-07-21T10:28:11.487 に答える