程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了clone element with beautifulsoup大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决clone element with beautifulsoup?

开发过程中遇到clone element with beautifulsoup的问题如何解决?下面主要结合日常开发的经验,给出你关于clone element with beautifulsoup的解决方法建议,希望对你解决clone element with beautifulsoup有所启发或帮助;

在4.4版 (2015年7月发布)之前的BeautifulSoup中没有本地克隆功能。您必须自己创建一个深层副本,这很 棘手,因为每个元素都维护着到树的其余部分的链接。

要克隆一个元素及其所有元素,您必须复制所有属性 并重置其父子关系。这必须递归地进行。 最好通过不复制关系属性并重新安置每个 递归克隆的元素来做到这一点:

from bs4 import Tag, NavigableString

def clone(el):
    if isinstance(el, NavigableString):
        return type(el)(el)

    copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefiX)
    # work around BUG where there is no builder set
    # https://BUGs.launchpad.net/beautifulsoup/+BUG/1307471
    copy.attrs = Dict(el.attrs)
    for attr in ('can_be_empty_element', 'hIDden'):
        setattr(copy, attr, getattr(el, attr))
    for child in el.contents:
        copy.append(clone(child))
    return copy

该方法对当前的BeautifulSoup版本敏感。我 使用4.3进行了测试,将来的版本可能还会添加需要 复制的属性。

您也可以将此功能猴子修补到BeautifulSoup中:

from bs4 import Tag, NavigableString


def tag_clone(self):
    copy = type(self)(None, self.builder, self.name, self.namespace, 
                      self.nsprefiX)
    # work around BUG where there is no builder set
    # https://BUGs.launchpad.net/beautifulsoup/+BUG/1307471
    copy.attrs = Dict(self.attrs)
    for attr in ('can_be_empty_element', 'hIDden'):
        setattr(copy, attr, getattr(self, attr))
    for child in self.contents:
        copy.append(child.clone())
    return copy


Tag.clone = tag_clone
NavigableString.clone = lambda self: type(self)(self)

让您.clone()直接调用元素:

document2.body.append(document1.find('div', ID_='somEID').clone())

我的功能要求,以对BeautifulSoup项目被接受,并 调整了使用COpy.copy()功能; 现在, BeautifulSoup 4.4已发布,您可以使用该版本(或更高版本)并执行以下操作:

import copy

document2.body.append(copy.copy(document1.find('div', ID_='somEID')))

解决方法

我必须将一个文档的一部分复制到另一个文档,但是我不想修改
从中复制的文档。

如果使用.extract()它,则从树中删除该元素。如果我只是追加
选定的元素,document2.append(document1.tag)它仍然会
从document1中删除该元素。

当我使用真实文件时,修改后我不能保存document1,但是
有什么方法可以做到不破坏文档?

大佬总结

以上是大佬教程为你收集整理的clone element with beautifulsoup全部内容,希望文章能够帮你解决clone element with beautifulsoup所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。