重写PythonMechanize.Browser.open()方法

2024-04-25 18:12:30 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码:

#!/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()

生成错误

^{pr2}$

我看了机械化代码和浏览器.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和Mechanize0.2.5的版本。在


Tags: selfbrowsernonedefaulturldatadeftimeout
1条回答
网友
1楼 · 发布于 2024-04-25 18:12:30

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

你不应该有这个问题。在

相关问题 更多 >