Python HTML删除

use*_*772 6 python string

如何从Python中删除字符串中的所有HTML?例如,我该怎么转:

blah blah <a href="blah">link</a>
Run Code Online (Sandbox Code Playgroud)

blah blah link
Run Code Online (Sandbox Code Playgroud)

谢谢!

Tri*_*ych 18

当您的正则表达式解决方案碰壁时,请尝试这个超级简单(可靠)的BeautifulSoup程序.

from BeautifulSoup import BeautifulSoup

html = "<a> Keep me </a>"
soup = BeautifulSoup(html)

text_parts = soup.findAll(text=True)
text = ''.join(text_parts)
Run Code Online (Sandbox Code Playgroud)


MrT*_*opf 10

还有一个名为stripogram的小型库,可用于删除部分或全部HTML标记.

你可以像这样使用它:

from stripogram import html2text, html2safehtml
# Only allow <b>, <a>, <i>, <br>, and <p> tags
clean_html = html2safehtml(original_html,valid_tags=("b", "a", "i", "br", "p"))
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces 
# and a page that's 80 characters wide.
text = html2text(original_html,ignore_tags=("img",),indent_width=4,page_width=80)
Run Code Online (Sandbox Code Playgroud)

因此,如果您想简单地删除所有HTML,则将valid_tags =()传递给第一个函数.

你可以在这里找到文档.


Luk*_*ard 7

您可以使用正则表达式删除所有标记:

>>> import re
>>> s = 'blah blah <a href="blah">link</a>'
>>> re.sub('<[^>]*>', '', s)
'blah blah link'
Run Code Online (Sandbox Code Playgroud)


jfs*_*jfs 5

如果属性中包含' ',则Regexs,BeautifulSoup,html2text 不起作用.请参阅html元素属性值中是否允许">"(U + 003E GREATER-THAN SIGN)?>

基于"HTML/XML解析器"的解决方案在这种情况下可能有所帮助,例如@MrTopf 建议的条形图确实有效.

这是基于ElementTree的解决方案:

####from xml.etree import ElementTree as etree # stdlib
from lxml import etree

str_ = 'blah blah <a href="blah">link</a> END'
root = etree.fromstring('<html>%s</html>' % str_)
print ''.join(root.itertext()) # lxml or ElementTree 1.3+
Run Code Online (Sandbox Code Playgroud)

输出:

blah blah link END
Run Code Online (Sandbox Code Playgroud)