使用 NTLM 进行 Python 机械化时出现 AttributeError: HTTPResponse 实例没有属性 '__iter__'

2023-11-29

我正在尝试使用 python-ntlm 和 mechanize 访问通过 NTLM 身份验证保护的网站,但出现此错误。

File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 203, in open
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 249, in _mech_open
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 304, in _set_response
File "build/bdist.macosx-10.6-universal/egg/mechanize/_response.py", line 521, in upgrade_response
File "build/bdist.macosx-10.6-universal/egg/mechanize/_response.py", line 338, in __init__
File "build/bdist.macosx-10.6-universal/egg/mechanize/_response.py", line 353, in _set_fp
AttributeError: HTTPResponse instance has no attribute '__iter__'

当我使用 urllib2 库时,我能够得到正确的响应。但由于某种原因,当我尝试使用 mechanize 访问它时,它失败了。

这是我的代码。

import urllib2
from ntlm import HTTPNtlmAuthHandler

user = '<myusername>'
password = "<mypass>"
url = "https://somesite.com"

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

import mechanize
browser = mechanize.Browser()
handlersToKeep = []

for handler in browser.handlers:
    if not isinstance(handler,
    (mechanize._http.HTTPRobotRulesProcessor)):
        handlersToKeep.append(handler)

browser.handlers = handlersToKeep
browser.add_handler(auth_NTLM)

response = browser.open(url)
print(response.read())

有人知道发生了什么事吗?我在这里做错了什么吗?


我修补了机械化来解决这个问题:

--- _response.py.old    2013-02-06 11:14:33.208385467 +0100
+++ _response.py    2013-02-06 11:21:41.884081708 +0100
@@ -350,8 +350,13 @@
             self.fileno = self.fp.fileno
         else:
             self.fileno = lambda: None
-        self.__iter__ = self.fp.__iter__
-        self.next = self.fp.next
+
+        if hasattr(self.fp, "__iter__"):
+            self.__iter__ = self.fp.__iter__
+            self.next = self.fp.next
+        else:
+            self.__iter__ = lambda self: self
+            self.next = lambda self: self.fp.readline()

     def __repr__(self):
         return '<%s at %s whose fp = %r>' % (
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 NTLM 进行 Python 机械化时出现 AttributeError: HTTPResponse 实例没有属性 '__iter__' 的相关文章

随机推荐