检查网站是否存在但请求不起作用

Mic*_*her 2 python web-scraping

因此,几天前我了解了 Web Scraping 的工作原理,而今天我却在胡闹。我想知道如何测试页面是否存在/不存在。所以,我了一下,我发现Python 检查网站是否存在。我正在使用requests module,我从答案中得到了这个代码:

import requests
request = requests.get('http://www.example.com')
if request.status_code == 200:
    print('Web site exists')
else:
    print('Web site does not exist') 
Run Code Online (Sandbox Code Playgroud)

我试了一下,因为example.com存在,它打印出“网站存在”。但是,我尝试了一些我确信不存在的东西,比如 examplewwwwwww.com 并且它给了我这个错误。为什么要这样做,我怎样才能防止它打印出错误(而是说该网站不存在)?

Ale*_* K. 5

您可以像这样使用 try/except:

import requests
from requests.exceptions import ConnectionError

try:
    request = requests.get('http://www.example.com')
except ConnectionError:
    print('Web site does not exist')
else:
    print('Web site exists')
Run Code Online (Sandbox Code Playgroud)