问题
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