@pcdesign

Как в тексте оставить ссылки вида href='#id' и удалить остальные?

Например, текст:
<p>Lorem Ipsum is simply dummy text of the printing and <a href="/ggg">typesetting</a> industry.
Lorem Ipsum has been the industry's standard <a href="#id">dummy</a> text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.</p>

<p>It has survived not only five centuries, but also
 the <a href="http://example.com">leap</a> into electronic typesetting...</p>


Ожидаемый результат:

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard <a href="#id">dummy</a> text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.</p>

<p>It has survived not only five centuries, but also the leap into electronic typesetting...</p>


Может есть какой-нибудь модуль, который бы умел это делать?
  • Вопрос задан
  • 82 просмотра
Решения вопроса 1
@pcdesign Автор вопроса
from bs4 import BeautifulSoup 
soup = BeautifulSoup(html, features="lxml")
for m in soup.find_all('a'):
    if 'href="#' not in str(m):
        m.replaceWithChildren()
print(soup)
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
netpastor
@netpastor
Python developer
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы