16

我正在尝试编写一个脚本来测试网页是否存在,如果它在不下载整个页面的情况下进行检查会很好。

这是我的出发点,我已经看到多个示例以相同的方式使用 httplib,但是,我检查的每个站点都只返回 false。

import httplib
from httplib import HTTP
from urlparse import urlparse

def checkUrl(url):
    p = urlparse(url)
    h = HTTP(p[1])
    h.putrequest('HEAD', p[2])
    h.endheaders()
    return h.getreply()[0] == httplib.OK

if __name__=="__main__":
    print checkUrl("http://www.stackoverflow.com") # True
    print checkUrl("http://stackoverflow.com/notarealpage.html") # False

有任何想法吗?

编辑

有人提出这个建议,但他们的帖子被删除了.. urllib2 是否避免下载整个页面?

import urllib2

try:
    urllib2.urlopen(some_url)
    return True
except urllib2.URLError:
    return False
4

4 回答 4

24

这个怎么样:

import httplib
from urlparse import urlparse

def checkUrl(url):
    p = urlparse(url)
    conn = httplib.HTTPConnection(p.netloc)
    conn.request('HEAD', p.path)
    resp = conn.getresponse()
    return resp.status < 400

if __name__ == '__main__':
    print checkUrl('http://www.stackoverflow.com') # True
    print checkUrl('http://stackoverflow.com/notarealpage.html') # False

如果响应状态码 < 400,这将发送一个 HTTP HEAD 请求并返回 True。

  • 请注意,StackOverflow 的根路径返回重定向 (301),而不是 200 OK。
于 2011-06-24T17:34:22.303 回答
14

使用requests,这很简单:

import requests

ret = requests.head('http://www.example.com')
print(ret.status_code)

这只是加载网站的标题。要测试这是否成功,您可以检查结果status_code。或者使用在连接不成功时raise_for_status引发的方法。Exception

于 2016-04-08T17:44:28.433 回答
5

这个怎么样。

import requests

def url_check(url):
    #Description

    """Boolean return - check to see if the site exists.
       This function takes a url as input and then it requests the site 
       head - not the full html and then it checks the response to see if 
       it's less than 400. If it is less than 400 it will return TRUE 
       else it will return False.
    """
    try:
            site_ping = requests.head(url)
            if site_ping.status_code < 400:
                #  To view the return status code, type this   :   **print(site.ping.status_code)** 
                return True
            else:
                return False
    except Exception:
        return False
于 2017-04-07T00:03:34.370 回答
-2

你可以试试

import urllib2

try:
    urllib2.urlopen(url='https://someURL')
except:
    print("page not found")
于 2016-04-08T17:35:31.840 回答