1

得到了我的小机械化代码:

br.open('http://tumblr.com/customize'); 
print br.response().read()
print br.form['edit_tumblelog[cname]'] # there definitely is edit_tumblelog
                                       # and br.form['edit_tumblelog[enable_cname]'] works fine

输出:

...
<br/>
                                    <input type="text" class="text_field" style="width:275px; min-width:0px;
                                    margin:6px 0px; border:solid 1px #d2d2d2;
                                    "
                                    name="cname" id="cname"
                                    onchange="form_changed = true;"
                                     value="blog.yay.com"    
                                    />
...
Traceback (most recent call last):
  File "/tmp/temp_textmate.W6p5gh", line 51, in <module>
    print br.form['edit_tumblelog[cname]']
  File "/Library/Python/2.6/site-packages/ClientForm-0.2.10-py2.6.egg/ClientForm.py", line 2891, in __getitem__
  File "/Library/Python/2.6/site-packages/ClientForm-0.2.10-py2.6.egg/ClientForm.py", line 3222, in find_control
  File "/Library/Python/2.6/site-packages/ClientForm-0.2.10-py2.6.egg/ClientForm.py", line 3306, in _find_control
ClientForm.ControlNotFoundError: no control matching name 'edit_tumblelog[cname]'

我究竟做错了什么?

4

2 回答 2

8

发现了问题。<br/>这是 Mechanize HTML 解析器中的一个错误,它会在出现正常工作的注释后以某种方式忽略下一个标记<br />。我的解决方案是手动替换那些:

response = br.response()
response.set_data(response.get_data().replace("<br/>", "<br />")) #Python mechanize is broken, fixing it.
br.set_response(response)

显然更好的解决方案是re.sub()所有标签前不加空格/>

于 2010-03-07T00:45:16.863 回答
6

也许这对任何人都感兴趣:

br = mechanize.Browser(factory=mechanize.RobustFactory())

这应该可以解决 HTML 解析器的问题。

于 2011-09-14T18:01:02.047 回答