【发布时间】:2014-04-23 10:30:42
【问题描述】:
由于我想删除 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 也不是我想要的。
【问题讨论】:
-
运行它时我没有得到相同的行为——我的输出不包括空行(这是我所期望的行为)。这正是你正在运行的吗?
-
绝对。我正在运行 python3.4 removeplaceholder.py 并得到 exactly 输出,包括换行符。
标签: python html-parsing beautifulsoup