html文件怎么去掉标签
时间: 2024-05-04 12:15:58 浏览: 10
您可以使用正则表达式或者专门的HTML解析库来去掉HTML标签。使用正则表达式的方法如下:
```python
import re
def remove_tags(text):
clean = re.compile('<.*?>')
return re.sub(clean, '', text)
html_text = '<html><head><title>Hello World!</title></head><body><p>This is a <b>sample</b> text.</p></body></html>'
clean_text = remove_tags(html_text)
print(clean_text)
# Output: Hello World!This is a sample text.
```
此方法将会删除文本中的所有HTML标签,返回纯文本。
当然也可以使用第三方库,比如`BeautifulSoup`:
```python
from bs4 import BeautifulSoup
html_text = '<html><head><title>Hello World!</title></head><body><p>This is a <b>sample</b> text.</p></body></html>'
soup = BeautifulSoup(html_text, 'html.parser')
clean_text = soup.get_text() # 获取纯文本
print(clean_text)
# Output: Hello World!This is a sample text.
```
这种方法会解析HTML并提供一些额外的功能,比如支持CSS选择器来定位特定的标签。