Skip to content

Commit

Permalink
Added bs.is_empty function
Browse files Browse the repository at this point in the history
  • Loading branch information
sgeulette committed Nov 18, 2023
1 parent f4a712e commit ad38d40
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Changelog
[sgeulette]
- Improved `utils_safe_encode`
[sgeulette]
- Added `bs.is_empty` function.
[sgeulette]
- Added `bs.remove_some_childrens` function.
[sgeulette]
- Added `bs.replace_strings_by_pattern` function
Expand Down
15 changes: 11 additions & 4 deletions imio/pyutils/bs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
import re


def is_empty(element):
"""Check if element has no text content nor children.
:param element: bs item
:return: Bool value (True is empty)
"""
return len(element.get_text(strip=True)) == 0 and len(list(element.children)) == 0


def remove_attributes(element, attributes=[], recursive=True):
""" Removes attributes on given element or recursively """
elements = [element]
Expand All @@ -31,22 +40,20 @@ def remove_childrens_by_pattern(parent, child_text_pat, name=None, recursive=Fal
:param name: optional children's tag
:param recursive: recursive children
:param keep: keep children at this position (starting at 1)
:return:
:return: list of removed items
"""
childrens = list(parent.find_all(name=name, recursive=recursive))
if isinstance(parent, BeautifulSoup):
childrens.pop(0)
removed = []
change = False
count = 0
for ch_t in childrens:
if found := re.search(child_text_pat, ch_t.text, re.I):
count += 1
if count not in keep:
change = True
removed.append(str(ch_t))
ch_t.decompose()
return change, removed
return removed


def remove_comments(element):
Expand Down

0 comments on commit ad38d40

Please sign in to comment.