# Sample XML file.
xml = """
<1 sno=1>
<2>
Some content
</2>
<2>
Some other content
</2>
<2>
Some more contents
</2>
</1>
<1 sno=2>
<2>
Some content
</2>
<2>
Some other content
</2>
<2>
Some more contents
</2>
</1>
<1 sno=3>
<2>
Some content
</2>
<2>
Some other content
</2>
<2>
Some more contents
</2>
</1>
"""
这是示例 XML 文件;我想处理所有 <1> 标签。
- 首先我需要找到所有 1 个标签,
- 其次,以列表的形式获取内容。我希望 <2> 是单独的列表元素。
例如我期待像
['<2>','some content','</2>' .....]
这样的列表 而不是这样['<2>Some content</2>' , ....]
_
from bs4 import BeautifulSoup as BS
xml = BS(xml)
xmlList = []
for line in xml.1:
xmlList.append(line)
print xmlList
# To grab multiple '1' tags:
from bs4 import BeautifulSoup as BS
xml = BS(xml)
xmlList = []
for line in xml.findall('1'):
xmlList.append(line)
print xmlList
显示类似 ['<2>Some content</2>' , ....]
的列表,这是我不想要的。
如果我使用 find_all()
抓取所有'1'标签的语句,结果是一样的。如何克服这个问题?
最佳答案
在添加到列表之前将结尾切掉怎么样?
for line in xml.findAll('1'): #also should be findAll() vs findall()
xmlList.append(line[:-4])
关于python - BeautifulSoup 迭代多个 XML 标签,提取字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23693110/