【发布时间】:2015-10-16 02:43:14
【问题描述】:
我正在尝试使用 BeautifulSoup 删除其中没有文本的标签。例如我有以下标签:
<p>
<p>
<br/>
</p>
</p>
或
<p>
<br/>
</p>
我有以下功能:
@staticmethod
def stripTagWithNoText(soup,tagname,**kwargs):
"""Strip tags with no text"""
#Make sure that soup and tags were defined
assert isinstance(tagname,str)
#Remove tags with no text
for tag in soup.find_all(tagname):
if tag.string:
continue
for subtag in tag.findChildren():
if subtag.string:
break
else:
continue
tag.extract()
不过,这也会删除如下标签:
<p>This is some random text</p>
谁能看出这有什么问题?
另外,假设我在 html 的末尾附加了以下内容:
<p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p>
有没有办法从类似于 string_text.strip() 的 html 末尾删除所有空格?
注意 我正在使用 Python3、bs4
【问题讨论】:
-
了解它的 bs3 还是 4...python 2 还是 3 会很有帮助。
-
我使用的是 Python3、bs4
-
如果答案对您不起作用,请发布有问题的 html,以便我可以使用真实的测试用例。
标签: python beautifulsoup