Python Mechanize to check if a server is available

試著忘記壹切 提交于 2019-12-13 16:15:55

问题


I'm trying to write a script which will read a file containing some urls and then open a browser instance using mechanize module. I'm just wondering how I can do so if some url does not exist or if the server is unreachable.

For Example

import mechanize  

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

What I want to know is how I will get information from mechanize if 192.168.1.30 is unreachable or if http returns 404 Error.


回答1:


from mechanize import Browser
browser = Browser()
response = browser.open('http://www.google.com')
print response.code

Or Use Python requests library.

Sample code demonstrating it:

>>>import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200



回答2:


Try something like this:

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

Output:

404

If you try 'http://www.google.foo' it will get you a tuple:

(-2, 'Name or service not known')



来源:https://stackoverflow.com/questions/13816633/python-mechanize-to-check-if-a-server-is-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!