【问题标题】:XML parsing using BeautifulSoup : retrieve multiple text contents with same id inside same document使用 BeautifulSoup 进行 XML 解析:在同一文档中检索具有相同 id 的多个文本内容
【发布时间】:2020-11-27 19:55:33
【问题描述】:

我正在尝试在单个文档(标签)中检索具有相同文档编号的多个文本内容

我的 XML 文件如下所示:

<doc>
<docnum>1234</docnum>
<p>text1</p>
<p>text2</p>
<p>text3</p>
<p>text4</p>
<p>text5</p>
<docdesc>only text</docdesc>
</doc>

<doc>
<docnum>789</docnum>
<p>text1</p>
<p>text2</p>
<p>text3</p>
<p>text4</p>
<p>text5</p>
<docdesc>only and only texts</docdesc>
</doc>

但是 BeautifulSoup 的 find_all() 和 find() 方法不能单独提取它们。 我的代码 sn-p 如下:

from bs4 import BeautifulSoup
with open('file.xml', 'r') as openfile:
    content = "".join(openfile.readlines())
    soupcontent = BeautifulSoup(content, "lxml")
    docnums = [str(t.text) for t in (soupcontent.findAll('docnum'))]
    doctexts = [str(t.text) for t in (soupcontent.find_all('p'))]
    for a, b in zip(docnums, doctexts):
        print(a + '\n' + b)

但不是将 doc1 的 docnum 与 doc1 的所有 p 匹配,而是匹配所有内容。 每个 find_all() 中的嵌套 for 循环也无济于事。到达doc标签末尾时无法停止

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    此脚本将为每个 &lt;doc&gt; 打印所有 &lt;docnum&gt;&lt;p&gt;&lt;docdesc&gt;

    from bs4 import BeautifulSoup
    
    txt = '''<doc>
    <docnum>1234</docnum>
    <p>text1</p>
    <p>text2</p>
    <p>text3</p>
    <p>text4</p>
    <p>text5</p>
    <docdesc>only text</docdesc>
    </doc>
    
    <doc>
    <docnum>789</docnum>
    <p>text1</p>
    <p>text2</p>
    <p>text3</p>
    <p>text4</p>
    <p>text5</p>
    <docdesc>only and only texts</docdesc>
    </doc>'''
    
    soup = BeautifulSoup(txt, 'html.parser')
    
    for doc in soup.select('doc'):
        print('docnum :', doc.docnum.text)
        print('text   :', [p.text for p in doc.select('p')])
        print('docdesc:', doc.docdesc.text)
        print('-' * 80)
    

    打印:

    docnum : 1234
    text   : ['text1', 'text2', 'text3', 'text4', 'text5']
    docdesc: only text
    --------------------------------------------------------------------------------
    docnum : 789
    text   : ['text1', 'text2', 'text3', 'text4', 'text5']
    docdesc: only and only texts
    --------------------------------------------------------------------------------
    

    编辑:要将数据存储在列表中,您可以:

    docnums   = []
    doctexts  = []
    
    for doc in soup.select('doc'):
        docnums.append(doc.docnum.text)
        doctexts.append([p.text for p in doc.select('p')])
    
    for n, t in zip(docnums, doctexts):
        print(n)
        print(' '.join(t))
    

    【讨论】:

    • 谢谢@Andrej。只是一个小问题,如果文档中的标签名称是 那么属性 .text 会起作用吗?
    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2015-04-02
    • 2015-01-19
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多