由于我想删除 html 网站中重复的占位符,因此我使用 BeautifulSoup 的 .next_sibling 运算符。只要重复项位于同一行,就可以正常工作(参见数据)。但有时它们之间有一个空行 - 所以我希望 .next_sibling 忽略它们(看看 data2)
这就是代码:
from bs4 import BeautifulSoup, Tag
data = "<p>method-removed-here</p><p>method-removed-here</p><p>method-removed-here</p>"
data2 = """<p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
"""
soup = BeautifulSoup(data)
string = 'method-removed-here'
for p in soup.find_all("p"):
while isinstance(p.next_sibling, Tag) and p.next_sibling.name== 'p' and p.text==string:
p.next_sibling.decompose()
print(soup)
数据输出符合预期:
<html><head></head><body><p>method-removed-here</p></body></html>
data2 的输出(需要修复):
<html><head></head><body><p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
<p>method-removed-here</p>
</body></html>
我在 BeautifulSoup4 文档中找不到有用的信息,并且 .next_element 也不是我想要的。
我可以通过解决方法解决这个问题。问题描述于BeautifulSoup 的 google 群组 https://groups.google.com/forum/#!topic/beautifulsoup/F3sdgObXbO4他们建议对 html 文件使用预处理器:
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
html = re.sub('\n', ' ', html) # convert newlines to spaces
# this preserves newline delimiters
html = re.sub('[\s]+<', '<', html) # remove whitespaces before opening tags
html = re.sub('>[\s]+', '>', html) # remove whitespaces after closing tags
return html
这不是最好的解决方案,但却是一个。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)