用< br>替换线路断裂;在标签中使用美丽的小组
我想使用beautifure
来解析一些html
,然后替换< blockQuote> 带有
< br>
标签的标签。这是非常困难的,因为< 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>
但是,此代码改编自此答案仅在内内没有html标签的情况下工作&lt; blockQuote&gt;
。但是,如果有(&lt; strong&gt; line 3&lt;/strong&gt;
),则element.String
is none
none ,上述失败。
是否有可以应付HTML标签的替代方法?
I want to parse some HTML
using BeautifulSoup
and replace any line breaks (\n
) that are within <blockquote>
tags with <br>
tags. It is extra difficult because the <blockquote>
may contain other HTML tags.
My current attempt:
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))
Output should be:
<p>Hello
there</p>
<blockquote>Line 1<br/>Line 2<br/><strong>Line 3</strong><br/>Line 4</blockquote>
However, this code, adapted from this answer only works if there are no HTML tags within the <blockquote>
. But if there are (the <strong>Line 3</strong>
) then element.string
is None
, and the above fails.
Is there an alternative that can cope with HTML tags?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种选择是使用
descendants
寻找navigablestring
s,然后仅替换这些,仅留下其他元素:输出:
此方法的优势是它没有触摸,例如,html注释:
变成
您可能期望的。
An alternative would be to use
descendants
to look forNavigableString
s, and replace just those, leaving other elements alone:Output:
An advantage of this approach is that it doesn't touch, for example, HTML comments:
is turned into
as you might expect.
在使用
替换()
时,选择更具体的元素并将元素本身作为String
上的元素本身工作要简单得多。这样,您就不必担心其他标签,否则这些标签会以对象形式出现,并且在
get_text()
的结果中不会表示为字符串。示例
输出
It is much simpler to select your elements more specific and work on the elements itself as
string
while usingreplace()
.This way you don't have to worry about other tags that would otherwise be present as objects and are not represented as string in result of
get_text()
.Example
Output