在Python中测试有效URL哪个更好

1 投票
2 回答
924 浏览
提问于 2025-04-17 13:54

我想检查一个特定的网址是否存在。

我找到了两种方法。

网址是:http://www.google.com

1.

import urllib2
response = urllib2.urlopen(url)
response.code  # check what is the response code

2.

import httplib 
conn = httplib.HTTPConnection(url) 
conn.request('HEAD', '/') 
response = conn.getresponse() 
if response.status == 200: # check the status code
    # do something

虽然这两种方法都能达到我的目的,但哪一种方法更好呢?

提前感谢大家的帮助。

2 个回答

2

你可以试试这样的做法,关键是通常你还想处理你遇到的错误,比如在获取网址时出现问题。

In [4]: import urllib2

In [5]: def test(url):
   ...:     try:
   ...:         response = urllib2.urlopen(url)
   ...:     except urllib2.HTTPError as e:
   ...:         return e.code,None
   ...:     return response.code,response

In [6]: test('http://www.google.com')
Out[6]: 
(200,
 <addinfourl at 154469068 whose fp = <socket._fileobject object at 0x92caa2c>>)

In [7]: test('http://www.google.com/foobar')
Out[7]: (404, None)

实际上,你还需要处理 urllib2.URLError 这个错误:

In [10]: def test(url):
    ...:     try:
    ...:         response = urllib2.urlopen(url)
    ...:     except urllib2.HTTPError as err:
    ...:         return err.code, None
    ...:     except urllib2.URLError as err:
    ...:         return err.reason, None
    ...:     return response.code,response

In [11]: test('http://www.google.foo')
Out[11]: (socket.gaierror(-2, 'Name or service not known'), None)
2

如果你问的问题表达得正确,那么这两种方法都不是完美的。

主要的问题是,你提到“url”,但你只检查了“http”这种类型。其实,网址可以有很多种类型:

ftp://ftp.funet.fi/pub/standards/RFC/rfc959.txt

file:///home/somesh/.bashrc

http://www.google.com

“httplib”对这些检查没什么用,因为它只能处理“http”这种类型。而“urllib2”就可以处理我提到的所有类型,但你不应该检查response.code。相反,你应该捕捉在资源不可用时会出现的异常,比如HTTPErrorURLError

撰写回答