我正在尝试查看一个 html 文件并从中删除所有标签,以便只留下文本,但我的正则表达式有问题。这是我目前所拥有的。
import urllib.request, re
def test(url):
html = str(urllib.request.urlopen(url).read())
print(re.findall('<[\w\/\.\w]*>',html))
html 是一个包含一些链接和文本的简单页面,但我的正则表达式无法识别 !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"and 'a href=".. ..”标签。谁能解释我需要在正则表达式中更改什么?
最佳答案
使用BeautifulSoup .使用 lxml .不要使用 regular expressions解析 HTML。
编辑 2010-01-29:这将是 lxml 的合理起点:
from lxml.html import fromstring
from lxml.html.clean import Cleaner
import requests
url = "https://stackoverflow.com/questions/2165943/removing-html-tags-from-a-text-using-regular-expression-in-python"
html = requests.get(url).text
doc = fromstring(html)
tags = ['h1','h2','h3','h4','h5','h6',
'div', 'span',
'img', 'area', 'map']
args = {'meta':False, 'safe_attrs_only':False, 'page_structure':False,
'scripts':True, 'style':True, 'links':True, 'remove_tags':tags}
cleaner = Cleaner(**args)
path = '/html/body'
body = doc.xpath(path)[0]
print cleaner.clean_html(body).text_content().encode('ascii', 'ignore')
您需要内容,所以您可能不需要任何 javascript 或 CSS。另外,大概您只需要正文中的内容,而不是头部的 HTML。继续阅读 lxml.html.clean看看你能轻松去掉什么。比正则表达式更聪明,不是吗?
此外,请注意 unicode 编码问题。您很容易得到无法打印的 HTML。
2012-11-08:从使用 urllib2 更改为 requests .只需使用请求!
关于python - 在python中使用正则表达式从文本中删除html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2165943/