使用Mechanize查找含有列表中字符串的表单输入字段标签?

2 投票
1 回答
1971 浏览
提问于 2025-04-17 00:29

现在我明白这个错误是什么意思了,但我很好奇为什么这个方法不管用,以及有没有其他方法可以完成同样的任务。我在使用Beautiful Soup时传递正则表达式,但发现Mechanize似乎不支持同样的功能,这让我有点失望。

TypeError: control label must be string-like

# first - as a default - set form inputs by their labels
for k in variables:
    for word in input_names[k]:
        for control in br.form.find_control(label=re.compile(word)):
            br.form.set_value(variables[k], name=control.name)

我的目标是匹配任何表单输入,其标签中包含某个短语,而不是完全匹配。

另外,如果有关于提高效率或让代码更优雅的建议,我会很感激;我刚开始学习python。

解决方法:(未经测试)

for tag in soup.findAll("label"):
    for k in variables:
        # try to find label in <label>X</label>. It will not be in for="X" 
        # because if it was, we'd find it below anyway.
            for word in input_names[k]:
                if word in  tag.contents.lower():
                    try:
                        br.form.find_control(name=tag['for'], kind="text").value = variables[k]
                    except:
                        print "failed to set value of input found by label."

1 个回答

1

假设 br.form.find_control() 这个方法不支持正则表达式,我们就得想其他办法,比如手动去找和匹配所有的控件。另一种方法是使用 BS(Beautiful Soup)结合正则表达式来匹配具体的文本,然后再把这个结果传回给 mechanize

撰写回答