Python去除html标签的几种方法总结?

Python去除html标签的方法

最近小说看得比较多,但是很多小说网站都存在各种小广告,看起来很不方便,所以就自己写了个小程序,把小说都爬下来,然后搭个自己喜欢web页面来看。

在爬取过程中没有出现太大的问题,只有在清洗数据时,发现小说文本中混杂HTML标签,所以就需要对标签进行清洗。

我自己尝试了字符串的处理方式,正则,还有lxml等方式来处理这个问题,现在记录一下使用方式。

我们使用下面这个字符串举例说明,内容为一段html代码。需要对这段字符串进行处理,提取文本

html = '<p>你好</p><br/><font>哈哈</font><b>大家好</b>'

1. 使用正则来处理

import re

pattern = re.compile(r'<[^>]+>',re.S)
result = pattern.sub('', html)
print(result)

输出结果:

你好哈哈大家好

2. 使用BeautifulSoup来处理

from bs4 import BeautifulSoup

soup = BeautifulSoup(html,'html.parser')
print(soup.get_text())

输出结果:

你好哈哈大家好

3. 使用lxml来出来

from lxml import etree

response = etree.HTML(text=html)
# print(dir(response))
print(response.xpath('string(.)'))

输出结果:

你好哈哈大家好

python正则表达式去除html标签的属性

import re
test='<p class="pictext" align="center">陈细妹</p>'
test=re.sub(r'(<[^>\s]+)\s[^>]+?(>)', r'\1\2', test)
print(test)

输出

<p>陈细妹</p>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/ares_beyong/article/details/121284781