python 过滤所有html标签
时间: 2023-10-12 09:21:11 浏览: 38
可以使用正则表达式来过滤所有的 HTML 标签,示例代码如下:
```python
import re
def remove_tags(html):
"""
过滤 HTML 标签
"""
pattern = re.compile(r'<[^>]+>')
return pattern.sub('', html)
html = '<p>Hello, <b>world</b>!</p>'
text = remove_tags(html)
print(text) # 输出: Hello, world!
```
上述代码中,`remove_tags` 函数接收一个 HTML 字符串作为参数,通过正则表达式的方式匹配所有的 HTML 标签,并将其替换为空字符串,从而过滤掉所有的 HTML 标签。
相关问题
正则表达式python过滤html标签,Python如何使用正则表达式去除HTML标签提取文字功能...
在Python中,可以使用正则表达式来过滤HTML标签并提取文字。以下是一个示例代码:
```python
import re
def remove_tags(html):
# 用正则表达式过滤HTML标签
clean = re.compile('<.*?>')
text = re.sub(clean, '', html)
return text
# 示例用法
html = '<p>Hello, <b>world!</b></p>'
text = remove_tags(html)
print(text) # 输出:Hello, world!
```
在上面的代码中,`remove_tags()` 函数接收一个包含HTML标签的字符串,然后使用正则表达式来过滤掉所有的HTML标签,并返回纯文本。这里使用的正则表达式 `<.*?>` 匹配任何以 `<` 开头、以 `>` 结尾的字符序列,这包括HTML标签以及其他字符序列,因此可以通过 `re.sub()` 函数将其替换为空字符串。
正则过滤html标签
可以使用正则表达式来过滤HTML标签,具体方法如下:
```python
import re
def remove_tags(html):
# 定义HTML标签的正则表达式
pattern = re.compile(r'<[^>]+>', re.S)
# 使用sub方法将HTML标签替换为空字符串
return pattern.sub('', html)
```