Pregunta

Digamos que quería eliminar las vocales de HTML:

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

se convierte

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

Me imagino que este es un trabajo para Beautiful Soup. ¿Cómo puedo seleccionar el texto entre etiquetas y operarlo de esta manera?

¿Fue útil?

Solución

Suponga que la variable test_html tiene el siguiente contenido html:

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

Solo haz esto:

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

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

Tenga en cuenta que las etiquetas y los atributos están intactos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top