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.
我正在编写一个脚本,它将读取一个包含url的文件,然后使用mechanize模块打开一个浏览器实例。我只是想知道,如果某个url不存在,或者服务器无法访问,我该怎么做。
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.
我想知道的是,如果192.168.1.30是不可访问的,或者http返回404错误,我将如何从机械化获取信息。
2 个解决方案
#1
-1
from mechanize import Browser
browser = Browser()
response = browser.open('http://www.google.com')
print response.code
Or Use Python requests library.
或者使用Python请求库。
Sample code demonstrating it:
示例代码演示:
>>>import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
#2
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:
如果你尝试http://www.google.foo,它会给你一个元组:
(-2, 'Name or service not known')
(-2,“不知道的名称或服务”)
#1
-1
from mechanize import Browser
browser = Browser()
response = browser.open('http://www.google.com')
print response.code
Or Use Python requests library.
或者使用Python请求库。
Sample code demonstrating it:
示例代码演示:
>>>import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
#2
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:
如果你尝试http://www.google.foo,它会给你一个元组:
(-2, 'Name or service not known')
(-2,“不知道的名称或服务”)