Mit Schöne Suppe, wie iterieren ich über alle eingebetteten Text?
-
06-07-2019 - |
Frage
Nehmen wir an, ich wollte von HTML Vokale entfernen:
<a href="foo">Hello there!</a>Hi!
wird
<a href="foo">Hll thr!</a>H!
Ich stelle dar, das ein Job für schöne Suppe ist. Wie kann ich den Text zwischen Tags auswählen und arbeiten auf es so?
Lösung
Angenommen, die Variable test_html
hat den folgenden HTML-Inhalt:
<html>
<head><title>Test title</title></head>
<body>
<p>Some paragraph</p>
Useless Text
<a href="http://stackoverflow.com">Some link</a>not a link
<a href="http://python.org">Another link</a>
</body></html>
Just dies zu tun:
from BeautifulSoup import BeautifulSoup
test_html = load_html_from_above()
soup = BeautifulSoup(test_html)
for t in soup.findAll(text=True):
text = unicode(t)
for vowel in u'aeiou':
text = text.replace(vowel, u'')
t.replaceWith(text)
print soup
Das druckt:
<html>
<head><title>Tst ttl</title></head>
<body>
<p>Sm prgrph</p>
Uslss Txt
<a href="http://stackoverflow.com">Sm lnk</a>nt lnk
<a href="http://python.org">Anthr lnk</a>
</body></html>
Beachten Sie, dass die Tags und Attribute sind unberührt.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow