Question

Disons que je voulais supprimer les voyelles du code HTML:

<a href="foo">Hello there!</a>Hi!

devient

<a href="foo">Hll thr!</a>H!

Je pense que c'est un travail pour Beautiful Soup. Comment puis-je sélectionner le texte entre les balises et l'utiliser comme ceci?

Était-ce utile?

La solution

Supposons que la variable test_html ait le contenu HTML suivant:

<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>

Faites ceci:

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

Qui imprime:

<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>

Notez que les balises et attributs ne sont pas modifiés.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top