Question

Je travaille sur un logiciel de grattage de l'écran et se sont heurtées à un problème avec soupe Belle. J'utilise python et beau 3.0.7a 2.4.3 soupe.

je supprimer une balise <hr>, mais il peut avoir plusieurs attributs différents, donc un simple appel remplacer () ne sera pas coupé.

Vu le code html suivant:

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

Et le code suivant:

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 sortie est la suivante:

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

je comprends mal la fonction d'extrait, ou est-ce un bug avec Beautiful Soup?

Était-ce utile?

La solution

Il peut être un bug. Mais heureusement pour vous, il y a une autre façon d'obtenir la chaîne:

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

Autres conseils

J'ai le même problème. Je ne sais pas pourquoi, mais je suppose que cela a à voir avec les éléments vides créés par BS.

Par exemple, si j'ai le code suivant:

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

Je suis l'erreur suivante:

  

objet 'NoneType' n'a pas d'attribut 'next_element'

Sur la première impression que je suis:

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

et le second je suis arrivé:

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

Je suis sûr qu'il est l'élément vide au milieu créant le problème.

Une solution que j'ai trouvé est de recréer juste la soupe:

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

Maintenant, il imprime:

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

J'espère que cela aide.

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