Pregunta

Estoy trabajando en algún software de captura de imágenes y se han topado con un problema con sopa de Hermosa. Estoy usando Python 2.4.3 y 3.0.7a sopa hermoso.

I que tenga que quitar una etiqueta <hr>, pero puede tener muchos atributos diferentes, por lo que una simple llamada replace () no se corte.

Dada la siguiente html:

<h1>foo</h1>
<h2><hr/>bar</h2>

Y el código siguiente:

soup = BeautifulSoup(string)

bad_tags = soup.findAll('hr');
[tag.extract() for tag in bad_tags] 

for i in soup.findAll(['h1', 'h2']):
    print i
    print i.string

La salida es:

<h1>foo</h1>
foo
<h2>bar</h2>
None

¿Estoy malentendido la función de extracción, o se trata de un error con sopa de Hermosa?

¿Fue útil?

Solución

Puede ser un error. Pero por suerte para usted, hay otra manera de obtener la cadena:

from BeautifulSoup import BeautifulSoup

string = \
"""<h1>foo</h1>
<h2><hr/>bar</h2>"""

soup = BeautifulSoup(string)

bad_tags = soup.findAll('hr');
[tag.extract() for tag in bad_tags] 

for i in soup.findAll(['h1', 'h2']):
    print i, i.next

# <h1>foo</h1> foo
# <h2>bar</h2> bar

Otros consejos

Tengo el mismo problema. No sé por qué, pero yo supongo que tiene que ver con los elementos vacíos creados por BS.

Por ejemplo si tengo el siguiente código:

from bs4 import BeautifulSoup

html ='            \
<a>                \
    <b test="help">            \
        hello there!  \
        <d>        \
        now what?  \
        </d>    \
        <e>        \
            <f>        \
            </f>    \
        </e>    \
    </b>        \
    <c>            \
    </c>        \
</a>            \
'

soup = BeautifulSoup(html,'lxml')
#print(soup.find('b').attrs)

print(soup.find('b').contents)

t = soup.find('b').findAll()
#t.reverse()
for c in t:
    gb = c.extract()

print(soup.find('b').contents)

soup.find('b').text.strip()

Tengo el siguiente error:

  

objeto 'NoneType' no tiene atributo 'next_element'

En la primera impresión que me dieron:

>>> print(soup.find('b').contents)
[u' ', <d> </d>, u' ', <e> <f> </f> </e>, u' ']

y en el segundo me dieron:

>>> print(soup.find('b').contents)
[u' ', u' ', u' ']

Estoy bastante seguro de que es el elemento vacío en el medio creando el problema.

Una solución que he encontrado es que acaba de volver a crear la sopa:

soup = BeautifulSoup(str(soup))
soup.find('b').text.strip()

Ahora se imprime:

>>> soup.find('b').text.strip()
u'hello there!'

Espero que ayude.

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