Skip to main content
 首页 » 编程设计

python之剥离 html 标签之间的空间

2025年05月04日15JustinYoung

我有一个包含一些 html 标签的字符串,如下所示:

"<p>   This is a   test   </p>" 

我想去掉标签之间的所有多余空格。我尝试了以下方法:

In [1]: import re 
 
In [2]: val = "<p>   This is a   test   </p>" 
 
In [3]: re.sub("\s{2,}", "", val) 
Out[3]: '<p>This is atest</p>' 
 
In [4]: re.sub("\s\s+", "", val) 
Out[4]: '<p>This is atest</p>' 
 
In [5]: re.sub("\s+", "", val) 
Out[5]: '<p>Thisisatest</p>' 

但我无法获得所需的结果,即 <p>This is a test</p>

我怎样才能做到这一点?

请您参考如下方法:

尝试使用类似 BeautifulSoup 的 HTML 解析器:

from bs4 import BeautifulSoup as BS 
s = "<p>   This is a   test   </p>" 
soup = BS(s) 
soup.find('p').string =  ' '.join(soup.find('p').text.split()) 
print soup 

返回:

<p>This is a test</p>