1

以下代码:

#!/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) 的第一个定义不起作用。它们不应该是等价的吗?这适用于带有机械化 0.2.5 的 python 2.6。

4

1 回答 1

2

第一个代码片段与其他两个代码片段的主要区别在于该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)

你不应该有这个问题。

于 2012-02-26T17:56:13.567 回答