python去掉html标签

= '<SPAN style="FONT- SIZE: 9pt">开始1~3<SPAN lang=EN-US>& lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></SPAN></SPAN>'
import re

= re.sub('<[^>]+>','',s)

利用正则式处理,不知道会不会有性能问题,没有经过太多测试。
目前我有很多还是使用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网页 图片 地图 资讯 视频 财经 更多 博客 生活 热榜 网站导航 日历 照片 文档 协作平台 输入法 工具栏 软件精选 更多 个性化首页 | 登录

from BeautifulSoup import BeautifulSoup
''.join(BeautifulSoup(page).findAll(text=True))

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

# -*- coding: utf-8-*-
import re
##过滤HTML中的标签
#将HTML中标签等信息去掉
#@param htmlstr HTML字符串.
def filter_tags(htmlstr):
    #先过滤CDATA
    re_cdata=re.compile('//<![CDATA[[^>]*//]]>',re.I) #匹配CDATA
    re_script=re.compile('<s*script[^>]*>[^<]*<s*/s*scripts*>',re.I)#Script
    re_style=re.compile('<s*style[^>]*>[^<]*<s*/s*styles*>',re.I)#style
    re_br=re.compile('<brs*?/?>')#处理换行
    re_h=re.compile('</?w+[^>]*>')#HTML标签
    re_comment=re.compile('<!--[^>]*-->')#HTML注释
    s=re_cdata.sub('',htmlstr)#去掉CDATA
    s=re_script.sub('',s) #去掉SCRIPT
    s=re_style.sub('',s)#去掉style
    s=re_br.sub(' ',s)#将br转换为换行
    s=re_h.sub('',s) #去掉HTML 标签
    s=re_comment.sub('',s)#去掉HTML注释
    #去掉多余的空行
    blank_line=re.compile(' +')
    s=blank_line.sub(' ',s)
    s=replaceCharEntity(s)#替换实体
    return s

##替换常用HTML字符实体.
#使用正常的字符替换HTML中特殊的字符实体.
#你可以添加新的实体字符到CHAR_ENTITIES中,处理更多HTML字符实体.
#@param htmlstr HTML字符串.
def replaceCharEntity(htmlstr):
    CHAR_ENTITIES={'nbsp':' ','160':' ',
                'lt':'<','60':'<',
                'gt':'>','62':'>',
                'amp':'&','38':'&',
                'quot':'"','34':'"',}
   
    re_charEntity=re.compile(r'&#?(?P<name>w+);')
    sz=re_charEntity.search(htmlstr)
    while sz:
        entity=sz.group()#entity全称,如&gt;
        key=sz.group('name')#去除&;后entity,如&gt;为gt
        try:
            htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1)
            sz=re_charEntity.search(htmlstr)
        except KeyError:
            #以空串代替
            htmlstr=re_charEntity.sub('',htmlstr,1)
            sz=re_charEntity.search(htmlstr)
    return htmlstr

def repalce(s,re_exp,repl_string):
    return re_exp.sub(repl_string,s)

if __name__=='__main__':
    s=file('Google.htm').read()
    news=filter_tags(s)
    print news

——————————————————华丽的分割线——————————————————————————

import urllib2,re
x=urllib2.urlopen('http://www.csdn.net').read()
re_h=re.compile('</?w+[^>]*>')
s=re_h.sub('',x)
print s

在这里只要将所有带<>去除即可:


dr = re.compile(r'<[^>]+>',re.S)
dd = dr.sub('',Html)

完整的python脚本:
第一个函数:将一个字段中的刮号去除
第二个函数:将html中的所有标签去除
    1. #!/usr/bin/env python  
    2. # -*- coding:utf-8 -*-  
    3.   
    4. import MySQLdb  
    5. import sys  
    6. import re  
    7.   
    8. conn = MySQLdb.connect(host='127.0.0.1',user='user',passwd='123456',db='hospital',charset='utf8')  
    9. cur = conn.cursor()  
    10.   
    11. def update_level():  
    12.     cur.execute("SELECT id,level FROM hospital where level like '(%)'")  
    13.     for row in cur.fetchall():  
    14.         sid=row[0]  
    15.         ii=re.sub('|','',row[1])  
    16.         sql = "update hospital set level=%s where id=%s"  
    17.         print sid,ii  
    18.         param = [ii,sid]  
    19.         cur.execute(sql,param)  
    20.   
    21. def update_detail():  
    22.     dr = re.compile(r'<[^>]+>',re.S)  
    23.     cur.execute("SELECT id,details FROM hospital")  
    24.     for row in cur.fetchall():  
    25.         did = row[0]  
    26.         detail=row[1]  
    27.         dd = dr.sub('',detail)  
    28.         sql="update hospital set details=%s where id=%s"  
    29.         param = (dd,did)  
    30.         cur.execute(sql,param)  
    31.         print "Finished",did  
    32.   
    33. def main():  
    34.     #update_level()  
    35.     update_detail()  
    36.   
    37. if __name__ == '__main__':  
    38.     main() 
原文地址:https://www.cnblogs.com/timssd/p/4735255.html