我想检查某个网站是否存在,这就是我正在做的:
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com"
req = urllib2.Request(link, headers = headers)
page = urllib2.urlopen(req).read() - ERROR 402 generated here!
如果页面不存在(错误 402 或任何其他错误),我可以在 page = ...
行中执行哪些操作以确保我正在阅读的页面确实存在退出?
最佳答案
您可以使用 HEAD 请求代替 GET。它只会下载标题,但不会下载内容。然后您可以从 header 中检查响应状态。
对于 python 2.7.x,您可以使用 httplib
:
import httplib
c = httplib.HTTPConnection('www.example.com')
c.request("HEAD", '')
if c.getresponse().status == 200:
print('web site exists')
或urllib2
:
import urllib2
try:
urllib2.urlopen('http://www.example.com/some_page')
except urllib2.HTTPError, e:
print(e.code)
except urllib2.URLError, e:
print(e.args)
或者对于 2.7 和 3.x,您可以安装 requests
import requests
response = requests.get('http://www.example.com')
if response.status_code == 200:
print('Web site exists')
else:
print('Web site does not exist')
关于Python 检查网站是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778435/