如何独立处理 xml 中的每段文本?replace_with 破坏孩子

我想对每段文本进行一次字符串替换,并保持树结构。


例如,每个字符串将被反转:abc > cba。


如果我将“replace_with()”应用于父节点,它只是连接嵌套文本,并展平父元素。


nodes = soup.find_all(['a','b'])

for node in nodes:

    rep = node.text[::-1]

    node.string.replace_with(rep)

输入:


<xml>

<a>abc

    <b>def </b>

    ghi

        <a>jkl 

            <b>mno</b>

        jkl </a>

    ghi

    <b>def </b>

abc</a>

</xml>

输出:


<xml> cba fed ihg    lkj ihg fed cbA </xml>

此外,在某些情况下(此处未显示)循环处理内部子项,并在父项处再次重新处理它们,导致混合结果;例如


abc def abc > cba def cba

我想找到一种方法来检索每段文本,并独立处理它。


如何?


哆啦的时光机
浏览 55回答 1
1回答

阿晨1998

您可以使用.find_all(text=True)仅查找文本节点然后处理它们。例如:txt = '''<xml><a>abc&nbsp; &nbsp; <b>def </b>&nbsp; &nbsp; ghi&nbsp; &nbsp; &nbsp; &nbsp; <a>jkl&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>mno</b>&nbsp; &nbsp; &nbsp; &nbsp; jkl </a>&nbsp; &nbsp; ghi&nbsp; &nbsp; <b>def </b>abc</a></xml>'''soup = BeautifulSoup(txt, 'html.parser')for t in soup.find_all(text=True):&nbsp; &nbsp; t.replace_with(t[::-1])print(soup.prettify())印刷:<xml>&nbsp;<a>&nbsp; cba&nbsp; <b>&nbsp; &nbsp;fed&nbsp; </b>&nbsp; ihg&nbsp; <a>&nbsp; &nbsp;lkj&nbsp; &nbsp;<b>&nbsp; &nbsp; onm&nbsp; &nbsp;</b>&nbsp; &nbsp;lkj&nbsp; </a>&nbsp; ihg&nbsp; <b>&nbsp; &nbsp;fed&nbsp; </b>&nbsp; cba&nbsp;</a></xml>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python