MCPcopy
hub / github.com/csev/py4e / insert

Method insert

code3/bs4/element.py:298–362  ·  view source on GitHub ↗
(self, position, new_child)

Source from the content-addressed store, hash-verified

296 _lastRecursiveChild = _last_descendant
297
298 def insert(self, position, new_child):
299 if new_child is None:
300 raise ValueError("Cannot insert None into a tag.")
301 if new_child is self:
302 raise ValueError("Cannot insert a tag into itself.")
303 if (isinstance(new_child, str)
304 and not isinstance(new_child, NavigableString)):
305 new_child = NavigableString(new_child)
306
307 position = min(position, len(self.contents))
308 if hasattr(new_child, 'parent') and new_child.parent is not None:
309 # We're 'inserting' an element that's already one
310 # of this object's children.
311 if new_child.parent is self:
312 current_index = self.index(new_child)
313 if current_index < position:
314 # We're moving this element further down the list
315 # of this object's children. That means that when
316 # we extract this element, our target index will
317 # jump down one.
318 position -= 1
319 new_child.extract()
320
321 new_child.parent = self
322 previous_child = None
323 if position == 0:
324 new_child.previous_sibling = None
325 new_child.previous_element = self
326 else:
327 previous_child = self.contents[position - 1]
328 new_child.previous_sibling = previous_child
329 new_child.previous_sibling.next_sibling = new_child
330 new_child.previous_element = previous_child._last_descendant(False)
331 if new_child.previous_element is not None:
332 new_child.previous_element.next_element = new_child
333
334 new_childs_last_element = new_child._last_descendant(False)
335
336 if position >= len(self.contents):
337 new_child.next_sibling = None
338
339 parent = self
340 parents_next_sibling = None
341 while parents_next_sibling is None and parent is not None:
342 parents_next_sibling = parent.next_sibling
343 parent = parent.parent
344 if parents_next_sibling is not None:
345 # We found the element that comes next in the document.
346 break
347 if parents_next_sibling is not None:
348 new_childs_last_element.next_element = parents_next_sibling
349 else:
350 # The last element of this tag is the last element in
351 # the document.
352 new_childs_last_element.next_element = None
353 else:
354 next_child = self.contents[position]
355 new_child.next_sibling = next_child

Callers 15

appendMethod · 0.95
updateLinesNoUndoFunction · 0.45
updateDocFunction · 0.45
updateDocFunction · 0.45
parse_argsMethod · 0.45
replace_withMethod · 0.45
unwrapMethod · 0.45
insert_beforeMethod · 0.45
insert_afterMethod · 0.45
test_new_tag_creationMethod · 0.45

Calls 5

minFunction · 0.85
NavigableStringClass · 0.70
indexMethod · 0.45
extractMethod · 0.45
_last_descendantMethod · 0.45