Skip to main content
 首页 » 编程设计

Python Mechanize 检查服务器是否可用

2025年05月04日6zlslch

我正在尝试编写一个脚本,该脚本将读取一个包含一些 url 的文件,然后使用 mechanize 模块打开一个浏览器实例。我只是想知道如果某些 url 不存在或服务器无法访问,我该怎么做。

例如

import mechanize   
 
br = mechanize.Browser()   
b  = br.open('http://192.168.1.30/index.php') 

我想知道的是,如果无法访问 192.168.1.30 或 http 返回 404 错误,我将如何从 mechanize 获取信息。

请您参考如下方法:

尝试这样的事情:

from mechanize import Browser 
b = Browser() 
try: 
    r=b.open('http://www.google.com/foobar') 
except (mechanize.HTTPError,mechanize.URLError) as e: 
    if isinstance(e,mechanize.HTTPError): 
        print e.code 
    else: 
        print e.reason.args 

输出:

404 

如果你尝试 'http://www.google.foo' 它会给你一个元组:

(-2, '名称或服务未知')