Заменить определенный символ, содержащийся в текстовой части строки HTML в Python - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть строка, которая является действительным 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?

1 Ответ

0 голосов
/ 02 ноября 2018

Вы можете использовать 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...