Python脚本如何判断网页是否存在而不下载整个页面?

18 投票
4 回答
21406 浏览
提问于 2025-04-16 20:14

我正在尝试写一个脚本来测试一个网页是否存在,如果能在不下载整个页面的情况下检查就更好了。

这是我开始的地方,我看到很多例子都用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 个回答

6

这样怎么样。

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
18

使用 requests 库,这样做就很简单:

import requests

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

这段代码只是加载了网站的头部信息。要检查这个操作是否成功,你可以查看结果中的 status_code。或者你也可以使用 raise_for_status 方法,如果连接不成功,它会抛出一个 Exception 错误。

25

这样做怎么样:

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

这段代码会发送一个HTTP的HEAD请求,如果返回的状态码小于400,就会返回True。

  • 注意,StackOverflow的根路径返回的是重定向(301),而不是200 OK。

撰写回答