以下代码:
#!/usr/bin/env python
import mechanize
class MechanizeSubclass(mechanize.Browser):
def __init__(self,
factory=None,
history=None,
request_class=None,
):
mechanize.Browser.__init__(self, factory, history, request_class)
def open(self, url, data=None,
timeout=mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
mechanize.Browser.open(self, url, data, timeout=timeout)
subclass = MechanizeSubclass()
subclass.open('https://uncjobs.northcarolina.edu/applicants/jsp/shared/Welcome_css.jsp')
print subclass.response().read()生成错误
mechanize._response.httperror_seek_wrapper: HTTP Error 302: Moved Temporarily我查看了机械化代码,Browser.open()方法的定义如下:
def open(self, url, data=None,
timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
return self._mech_open(url, data, timeout=timeout)如果我在我的子类中修改open()方法来匹配下面的代码:
class MechanizeSubclass(mechanize.Browser):
...
def open(self, url, data=None,
timeout=mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
return self._mech_open(url, data, timeout=timeout)那么它工作得很好。但是我仍然不能真正理解为什么第一个使用mechanize.Browser.open(self,url,data,timeout=timeout)的定义不能工作。它们不应该是等价的吗?这是在Python2.6和mechanize 0.2.5中实现的。
发布于 2012-02-27 01:56:14
第一个代码片段与其他两个代码片段之间的主要区别在于,open方法不返回任何内容(在Python语言中,这与返回None对象相同)。
也就是说,无论调用什么代码,open方法都希望由_mech_open返回对象。您的第一个方法不返回任何内容。
如果您只需将第一个实现更改为:
class MechanizeSubclass(mechanize.Browser):
...
def open(self, url, data=None,
timeout=mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
return mechanize.Browser.open(self, url, data, timeout=timeout)你应该不会有这个问题。
https://stackoverflow.com/questions/9455071
复制相似问题