[英]Replace a certain character contained in text part of an HTML string in Python
我有一個有效的HTML字符串,例如
s = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>"""
我想更換一個特定字符,比如a
在此字符串x
,病情暫時只有a
在HTML的內部文本發生的歷史將被更換,任何a
是標記標簽或值的一部分,不應該被更換。
我嘗試使用BeautifulSoup及其get_text()
方法,但這不能解決我的目的。 有什么辦法可以在Python中實現嗎?
您可以使用BeautifulSoup為您提供文檔中所有文本元素的列表。 然后,對於其中的每一個,您都可以使用replace_with()
函數將NavigableString
對象替換為更新版本,在您的情況下,將替換為必需的字符:
from bs4 import BeautifulSoup, NavigableString
s = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>"""
soup = BeautifulSoup(s, "html.parser")
for text in list(soup.strings):
text.replace_with(NavigableString(text.replace('a', 'x')))
print(soup)
因此,替換所有a
與人物x
會給你:
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon x time there were three little sisters; xnd their nxmes were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lxcie</a> xnd
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
xnd they lived xt the bottom of x well.</p>
<p class="story">...</p></body></html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.