【发布时间】:2022-02-09 20:26:54
【问题描述】:
我正在努力解决这个问题,该文件的根为“articles”,并且在标签“article>”下包含许多单独的文章。我希望做的是为“文章”中的每个“文章”收集“p”标签中的所有文本。一个“文章”可以有多个“p”标签,如下所示:
<articles>
<article title="Blah" published-at="2018-01-01" id="00000">
<p>Here is some text.</p>
<p>Another line of text.</p>
<a type="external" href="https://www.website.com/">Image</a>
<p>Final line of text.</p>
</article>
<article title="Second blah" published-at="2018-01-02" id="00001">
<p>Here is some new text.</p>
<p>Final line of new text.</p>
</article>
</articles>
所以我想做的是遍历每篇文章并生成包含“p”标签中所有文本的单行,而不关心我是否在“a”标签中拾取链接和相关文本。
我希望这样的事情能奏效,但它生成的文本文件没有被每个“文章”分隔
text = []
for p in root.iter('p'):
text.append(p.text)
with open("text.txt", "w", encoding = 'utf-8') as output:
output.write(str(text))
任何帮助将不胜感激,因为这对我来说是一个很难在搜索中表达的问题。
【问题讨论】:
标签: xml python-3.x