簡體   English   中英

使用Python中的Mechanize獲取和捕獲HTTP響應

[英]Getting and trapping HTTP response using Mechanize in Python

我試圖從python中的Mechanize獲取響應代碼。 雖然我能夠獲得200狀態代碼,但不會返回任何其他內容(404拋出異常,30x被忽略)。 有沒有辦法獲得原始狀態代碼?

謝謝

錯誤會引發異常,所以只需使用try:... except:...來處理它們。

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

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

在twill中,執行get_browser().get_code()

twill是一個出色的自動化和測試層,建立在機械化之上,使其更易於使用。 它非常方便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM