2010-04-20 57 views

回答

13

錯誤會拋出異常,所以只使用try:...除了:...來處理它們。

您的機械化瀏覽器對象有一個方法set_handle_redirect(),您可以使用該方法打開或關閉30x重定向。關閉它,你會得到一個錯誤,你處理就像你處理任何其他錯誤重定向:

>>> from mechanize import Browser 
>>> browser = Browser() 
>>> resp = browser.open('http://www.oxfam.com') # this generates a redirect 
>>> resp.geturl() 
'http://www.oxfam.org/' 
>>> browser.set_handle_redirect(False) 
>>> resp = browser.open('http://www.oxfam.com') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "build\bdist.win32\egg\mechanize\_mechanize.py", line 209, in open 
    File "build\bdist.win32\egg\mechanize\_mechanize.py", line 261, in _mech_open 
mechanize._response.httperror_seek_wrapper: HTTP Error 301: Moved Permanently 
>>> 
>>> from urllib2 import HTTPError 
>>> try: 
... resp = browser.open('http://www.oxfam.com') 
... except HTTPError, e: 
... print "Got error code", e.code 
... 
Got error code 301 
0

在斜紋布,做get_browser().get_code()

twill是建立在機械化的頂部突出的自動化和測試層,使其更易於使用。這非常方便。