我正在用美丽的汤解析一些 html 表单。基本上我有大约 60 个输入字段,主要是单选按钮和复选框。到目前为止,这适用于以下代码:
from BeautifulSoup import BeautifulSoup
x = open('myfile.html','r').read()
out = open('outfile.csv','w')
soup = BeautifulSoup(x)
values = soup.findAll('input',checked="checked")
# echoes some output like ('name',1) and ('value',4)
for cell in values:
# the following line is my problem!
statement = cell.attrs[0][1] + ';' + cell.attrs[1][1] + ';\r'
out.write(statement)
out.close()
x.close()
如代码中所示,我的问题是选择属性的位置,因为 HTML 模板很丑陋,混淆了属于输入字段的参数序列。我对 name="somenumber" value="someothernumber" 感兴趣。不幸的是,我的 attrs[1] 方法不起作用,因为名称和值在我的 html 中不会以相同的顺序出现。
有什么方法可以关联地访问生成的 BeautifulSoup 列表?
提前谢谢任何建议!