diff options
| author | Leonard Richardson <leonardr@segfault.org> | 2021-06-01 19:58:18 -0400 |
|---|---|---|
| committer | Leonard Richardson <leonardr@segfault.org> | 2021-06-01 19:58:18 -0400 |
| commit | 70f546b1e689a70e2f103795efce6d261a3dadf7 (patch) | |
| tree | e803f70d1e1e5625c8f31e5495201f0be462cb3d /bs4/element.py | |
| parent | a00624d7fc2e29b41b286f46844cb75f4d96ff63 (diff) | |
The 'replace_with()' method now takes a variable number of arguments,
and can be used to replace a single element with a sequence of elements.
Patch by Bill Chandos.
Diffstat (limited to 'bs4/element.py')
| -rw-r--r-- | bs4/element.py | 15 |
1 files changed, 8 insertions, 7 deletions
diff --git a/bs4/element.py b/bs4/element.py index 3428e21..e7867a9 100644 --- a/bs4/element.py +++ b/bs4/element.py @@ -296,25 +296,26 @@ class PageElement(object): getText = get_text text = property(get_text) - def replace_with(self, replace_with): - """Replace this PageElement with another one, keeping the rest of the - tree the same. + def replace_with(self, *args): + """Replace this PageElement with one or more PageElements, keeping the + rest of the tree the same. - :param replace_with: A PageElement. + :param args: One or more PageElements. :return: `self`, no longer part of the tree. """ if self.parent is None: raise ValueError( "Cannot replace one element with another when the " "element to be replaced is not part of a tree.") - if replace_with is self: + if len(args) == 1 and args[0] is self: return - if replace_with is self.parent: + if any(x is self.parent for x in args): raise ValueError("Cannot replace a Tag with its parent.") old_parent = self.parent my_index = self.parent.index(self) self.extract(_self_index=my_index) - old_parent.insert(my_index, replace_with) + for idx, replace_with in enumerate(args, start=my_index): + old_parent.insert(idx, replace_with) return self replaceWith = replace_with # BS3 |
