Python:使用正则去除HTML标签(转)

利用正则式处理,不知道会不会有性能问题,没有经过太多测试。
目前我有很多还是使用BeautifulSoup进行这种处理。
HTML实体处理的只是用于处理一些常用的实体。

 1 # -*- coding: utf-8-*-
 2 import re
 3 ##过滤HTML中的标签
 4 #将HTML中标签等信息去掉
 5 #@param htmlstr HTML字符串.
 6 def filter_tags(htmlstr):
 7 #先过滤CDATA
 8     re_cdata=re.compile('//<![CDATA[[^>]*//]]>',re.I) #匹配CDATA
 9     re_script=re.compile('<s*script[^>]*>[^<]*<s*/s*scripts*>',re.I)#Script
10     re_style=re.compile('<s*style[^>]*>[^<]*<s*/s*styles*>',re.I)#style
11     re_br=re.compile('<brs*?/?>')#处理换行
12     re_h=re.compile('</?w+[^>]*>')#HTML标签
13     re_comment=re.compile('<!--[^>]*-->')#HTML注释
14     s=re_cdata.sub('',htmlstr)#去掉CDATA
15     s=re_script.sub('',s) #去掉SCRIPT
16     s=re_style.sub('',s)#去掉style
17     s=re_br.sub('
',s)#将br转换为换行
18     s=re_h.sub('',s) #去掉HTML 标签
19     s=re_comment.sub('',s)#去掉HTML注释
20 #去掉多余的空行
21     blank_line=re.compile('
+')
22     s=blank_line.sub('
',s)
23     s=replaceCharEntity(s)#替换实体
24 return s
25 
26 ##替换常用HTML字符实体.
27 #使用正常的字符替换HTML中特殊的字符实体.
28 #你可以添加新的实体字符到CHAR_ENTITIES中,处理更多HTML字符实体.
29 #@param htmlstr HTML字符串.
30 def replaceCharEntity(htmlstr):
31     CHAR_ENTITIES={'nbsp':' ','160':' ',
32 'lt':'<','60':'<',
33 'gt':'>','62':'>',
34 'amp':'&','38':'&',
35 'quot':'"','34':'"',}
36 
37     re_charEntity=re.compile(r'&#?(?P<name>w+);')
38     sz=re_charEntity.search(htmlstr)
39 while sz:
40         entity=sz.group()#entity全称,如&gt;
41         key=sz.group('name')#去除&;后entity,如&gt;为gt
42 try:
43             htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1)
44             sz=re_charEntity.search(htmlstr)
45 except KeyError:
46 #以空串代替
47             htmlstr=re_charEntity.sub('',htmlstr,1)
48             sz=re_charEntity.search(htmlstr)
49 return htmlstr
50 
51 def repalce(s,re_exp,repl_string):
52 return re_exp.sub(repl_string,s)
53 
54 if __name__=='__main__':
55     s=file('Google.htm').read()
56     news=filter_tags(s)
57 print news

输出结果:

Google网页 图片 地图 资讯 视频 财经 更多 博客 生活 热榜 网站导航 日历 照片 文档 协作平台 输入法 工具栏 软件精选 更多 个性化首页 | 登录


高级搜索

使用偏好

语言工具所有网页 中文网页 简体中文网页 中国的网页

广告计划 – Google 大全 – Google.com in English2009 – 隐私权 – ICP证合字B2-20070004号

原文地址:https://www.cnblogs.com/mmix2009/p/3220990.html