Removes all elements with the given tagname and attributes from the string. Open and close tags are kept in balance. No HTML parser is used: strip_element(s, "a", "href='foo' class='bar'") matches "<a href='foo' class='bar'" but not "<a class='bar' href='foo'".
(string, tag, attributes="")
| 763 | strip_tags = HTMLTagstripper().strip |
| 764 | |
| 765 | def strip_element(string, tag, attributes=""): |
| 766 | """ Removes all elements with the given tagname and attributes from the string. |
| 767 | Open and close tags are kept in balance. |
| 768 | No HTML parser is used: strip_element(s, "a", "href='foo' class='bar'") |
| 769 | matches "<a href='foo' class='bar'" but not "<a class='bar' href='foo'". |
| 770 | """ |
| 771 | s = string.lower() # Case-insensitive. |
| 772 | t = tag.strip("</>") |
| 773 | a = (" " + attributes.lower().strip()).rstrip() |
| 774 | i = 0 |
| 775 | j = 0 |
| 776 | while j >= 0: |
| 777 | i = s.find("<%s%s" % (t, a), i) |
| 778 | j = s.find("</%s>" % t, i+1) |
| 779 | opened, closed = s[i:j].count("<%s" % t), 1 |
| 780 | while opened > closed and j >= 0: |
| 781 | k = s.find("</%s>" % t, j+1) |
| 782 | opened += s[j:k].count("<%s" % t) |
| 783 | closed += 1 |
| 784 | j = k |
| 785 | if i < 0: return string |
| 786 | if j < 0: return string[:i] |
| 787 | string = string[:i] + string[j+len(t)+3:]; s=string.lower() |
| 788 | return string |
| 789 | |
| 790 | def strip_between(a, b, string): |
| 791 | """ Removes anything between (and including) string a and b inside the given string. |
no test coverage detected
searching dependent graphs…