gpt4 book ai didi

python - Mechanize 无法读取带有禁用且没有值的 SubmitControl 的表单

转载 作者:太空狗 更新时间:2023-10-29 20:59:29 28 4
gpt4 key购买 nike

我正在尝试使用 mechanize (v0.2.5) 来处理页面上的表单,该页面将禁用图像作为表单元素之一。当我尝试选择表单时,mechanize 引发了 AttributeError: control 'test' is disabled 其中 test 是禁用控件的名称。例如,

br = mechanize.Browser(factory=mechanize.RobustFactory())
br.open("http://whatever...")
br.select_form(nr=0)

导致此堆栈跟踪:

    br.select_form(nr=0)
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 499, in select_form
File "build\bdist.win32\egg\mechanize\_html.py", line 544, in __getattr__
File "build\bdist.win32\egg\mechanize\_html.py", line 557, in forms
File "build\bdist.win32\egg\mechanize\_html.py", line 237, in forms
File "build\bdist.win32\egg\mechanize\_form.py", line 844, in ParseResponseEx
File "build\bdist.win32\egg\mechanize\_form.py", line 1017, in _ParseFileEx
File "build\bdist.win32\egg\mechanize\_form.py", line 2735, in new_control
File "build\bdist.win32\egg\mechanize\_form.py", line 2336, in __init__
File "build\bdist.win32\egg\mechanize\_form.py", line 1221, in __setattr__
AttributeError: control 'test' is disabled

检查 mechanize 源代码,当有任何表单元素的计算结果为 mechanize.SubmitControl 并且没有预定义的 value 时,似乎总是会引发此错误 属性。例如,以下形式会引发相同的错误:

<form action="http://whatever" method="POST">
<input name="test" type="submit" disabled="disabled" />
</form>

我不确定这是否应该算作错误,但无论如何有解决方法吗?例如,有没有一种方法可以在调用 br.select_form() 之前更改目标页面的 HTML 以启用禁用的控件?

编辑

我已经提交了一个补丁来解决这个问题。

最佳答案

可悲的是,已经一年多了,上游的 Mechanize 已经still not merged the pull request .

与此同时,您可以使用我编写的这个猴子补丁来解决该错误,而无需手动安装补丁版本。希望当(如果)0.2.6 发布时这个错误将得到解决,因此该补丁仅适用于 0.2.5 及更早版本。

def monkeypatch_mechanize():
"""Work-around for a mechanize 0.2.5 bug. See: https://github.com/jjlee/mechanize/pull/58"""
import mechanize
if mechanize.__version__ < (0, 2, 6):
from mechanize._form import SubmitControl, ScalarControl

def __init__(self, type, name, attrs, index=None):
ScalarControl.__init__(self, type, name, attrs, index)
# IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it
# blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem
# to define this.
if self.value is None:
if self.disabled:
self.disabled = False
self.value = ""
self.disabled = True
else:
self.value = ""
self.readonly = True

SubmitControl.__init__ = __init__

关于python - Mechanize 无法读取带有禁用且没有值的 SubmitControl 的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249996/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com