Python 检查网站是否存在

标签 python html urlopen

我想检查某个网站是否存在,这就是我正在做的:

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/

相关文章:

python - opencv 在 osx 上安装没有合适的图像错误

python - 在 Python 中记录模块/类/函数体 Sphinx 文档

javascript - 在kineticJS中检测单个对象上的放置事件

javascript - 如何使用 JavaScript 连接两个 html 元素数组

javascript - 如何使 javascript if 语句不接受除数值之外的任何内容

python - 用 Python 抓取网站的第二页不起作用

python - 子列表每个位置的正则表达式模式的频率

python - 使 eyeD3 模块可用于在 python 中导入

Python 3.6.3 urlopen 从存储在远程服务器上的 html 文件的 URI 中删除服务器名称

python - macOS Sierra/Python2.7.13 URLError : <urlopen error EOF occurred in violation of protocol (_ssl. c:661)>