首页 文章

将一个美丽的汤分成两个汤树

提问于
浏览
1

有多种方法可以分割beautifulSoup parsetree获取元素列表或获取标记的字符串 . 但是在分裂时似乎没有办法保持树完好无损 .

我想在
上分割下面的片段(汤) . 琐碎的字符串,但我想保留结构,我想要一个parsetrees列表 .

s="""<p>
foo
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar </p>""" soup=BeautifulSoup(s)

显然,我可以做一个 [BeautifulSoup(i) for i in str(soup).split('
')]
,但是我很难看,而且我的链接太多了 .

可以在soup.findAll('br')上使用soup.next和soup.previousSibling()进行迭代,但不返回分析树,而只返回它包含的所有元素 .

是否有解决方案从BeautifulSoup标签中提取完整的标签子树,保留所有父母和兄弟关系?

编辑以获得更清晰:

结果应该是一个由BeautifulSoup-Objects组成的列表,我可以通过输出[0] .a,输出[1] .text等进一步遍历分裂的汤 . 在
上拆分汤会返回所有要进一步处理的链接的列表,这就是我需要的 . 上面的代码段中的所有链接,包含文本,属性和以下"bar",是每个链接的说明 .

1 回答

  • 0

    如果您不在
    标签上使用 .extract() 来简单地从树中删除它们:

    >>> for br in soup.find_all('br'): br.extract()
    ... 
    



    >>> soup <html><body><p> foo <a href="http://...html" target="_blank">foo</a> | bar <a href="http://...html" target="_blank">foo</a> | bar <a href="http://...html" target="_blank">foo</a> | bar <a href="http://...html" target="_blank">foo</a> | bar </p></body></html>

    这是一个完整的工作树仍然:

    >>> soup.p
    <p>
    foo
    <a href="http://...html" target="_blank">foo</a> | bar
    <a href="http://...html" target="_blank">foo</a> | bar
    <a href="http://...html" target="_blank">foo</a> | bar
    <a href="http://...html" target="_blank">foo</a> | bar
    </p>
    >>> soup.p.a
    <a href="http://...html" target="_blank">foo</a>
    

    但是你根本不需要删除那些标签来实现你想要的东西:

    for link in soup.find_all('a'):
        print link['href'], ''.join(link.stripped_strings), link.next_sibling
    

    结果是:

    >>> for link in soup.find_all('a'):
    ...     print link['href'], ''.join(link.stripped_strings), link.next_sibling
    ... 
    http://...html foo  | bar
    http://...html foo  | bar
    http://...html foo  | bar
    http://...html foo  | bar
    

    无论有没有,我们首先从树中删除
    标签 .

相关问题