Python检查网站是否存在

Python检查网站是否存在

本文介绍了Python检查网站是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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() - 这里产生的错误402!

如果页面不存在(错误402或任何其他错误),我该怎么办在 page = ... 行中,确保我正在阅读的页面确实退出?

解决方案

您可以使用HEAD请求而不是GET。它只会下载标题,而不是内容。然后你可以检查头部的响应状态。

  import httplib 
c = httplib.HTTPConnection('www.example .com')
c.request(HEAD,'')
if c.getresponse()。status == 200:
print('web site exists')

或者您可以使用 urllib2

 导入urllib2 
尝试:
urllib2.urlopen('http://www.example.com/some_page')
除了urllib2.HTTPError,e:
print(e.code)
,除了urllib2.URLError,e:
print(e.args)

或者您可以使用请求

 导入请求
request = requests.get('http://www.example.com')
if request.status_code == 200:
print('网站存在')
其他:
print('网站不存在')


I wanted to check if a certain website exists, this is what I'm doing:

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!

If the page doesn't exist (error 402, or whatever other errors), what can I do in the page = ... line to make sure that the page I'm reading does exit?

解决方案

You can use HEAD request instead of GET. It will only download the header, but not the content. Then you can check the response status from the headers.

import httplib
c = httplib.HTTPConnection('www.example.com')
c.request("HEAD", '')
if c.getresponse().status == 200:
   print('web site exists')

or you can use 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)

or you can use requests

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')

这篇关于Python检查网站是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:49