[英]Python and Beautiful soup - getting values and saving them in a text file
我有一个XML文件,其中包含许多相关信息的记录,如下所示
<file>
<record>
<type>a</type>
<number>2</number>
</record>
<record>
<type>b</type>
<number>9</number>
</record>
等等
我希望BS读取所有XML文件并按列提供结果:
a2
b 9等
编辑
谢谢大家参与。我安装了xml解析器,并且使用的是bs4 xml模式。 我不再收到错误,但是我得到了:
b
2 9
代替
a2
b 9
新代码:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('file.xml'),"xml")
with open('output.txt') as f:
for type1,number in (soup.findall('type'),soup.findall('number')):
f.write ('%s\t%s\n' % (type1.text, number.text))
第二次编辑:
如果在XML文件中添加第3条记录,则会出现以下错误
追溯(最近一次调用):文件“ multixmlsript.py”,第8行,用于type1,number in(soup.findAll('type'),soup.findAll('number')):ValueError:值太多打开包装
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(open('path/to/file'))
with open('/path/to/output.txt', 'w') as f:
for i in range(len(soup.findAll('type'))):
f.write ('%s\t%s\n' % (soup.findAll('type')[i].text, soup.findAll('number')[i].text))
您已经将BeautifulSoup
用于HTML。 但是您需要对XML使用BeautifulStoneSoup
。 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.