【发布时间】:2022-07-07 19:53:58
【问题描述】:
我想使用BeautifulSoup 解析一些HTML 并用<br> 标记替换<blockquote> 标记内的任何换行符(\n)。这更加困难,因为<blockquote> 可能包含其他 HTML 标记。
我目前的尝试:
from bs4 import BeautifulSoup
html = """
<p>Hello
there</p>
<blockquote>Line 1
Line 2
<strong>Line 3</strong>
Line 4</blockquote>
"""
soup = BeautifulSoup(html, "html.parser")
for element in soup.findAll():
if element.name == "blockquote":
new_content = BeautifulSoup(
"<br>".join(element.get_text(strip=True).split("\n")).strip("<br>"),
"html.parser",
)
element.string.replace_with(new_content)
print(str(soup))
输出应该是:
<p>Hello
there</p>
<blockquote>Line 1<br/>Line 2<br/><strong>Line 3</strong><br/>Line 4</blockquote>
然而,这个改编自this answer 的代码只有在<blockquote> 中没有HTML 标记时才有效。但是如果有(<strong>Line 3</strong>)那么element.string就是None,上面的就失败了。
有没有可以处理 HTML 标签的替代方案?
【问题讨论】:
标签: python html web-scraping beautifulsoup