Domanda

Sono parsing del codice HTML con Beautiful Soup 3, ma contiene le entità HTML che Beautiful Soup 3 non decodifica automaticamente per me:

>>> from BeautifulSoup import BeautifulSoup

>>> soup = BeautifulSoup("<p>&pound;682m</p>")
>>> text = soup.find("p").string

>>> print text
&pound;682m

Come faccio a decodificare le entità HTML in text per ottenere "£682m" invece di "&pound;682m".

È stato utile?

Soluzione

Python 3.4 +

html.unescape() :

import html
print(html.unescape('&pound;682m'))

FYI html.parser.HTMLParser.unescape è deprecato, e doveva essere rimosso in 3,5 , anche se è stato lasciato in per errore. Sarà rimosso dalla lingua al più presto.


Python 2.6-3.3

È possibile utilizzare HTMLParser.unescape() dalla libreria standard:

>>> try:
...     # Python 2.6-2.7 
...     from HTMLParser import HTMLParser
... except ImportError:
...     # Python 3
...     from html.parser import HTMLParser
... 
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

È inoltre possibile utilizzare il href="https://pythonhosted.org/six/" rel="noreferrer"> six libreria di compatibilità

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

Altri suggerimenti

Beautiful Soup gestisce la conversione entità. In Beautiful Soup 3, è necessario specificare l'argomento convertEntities al costruttore BeautifulSoup (vedere la sezione 'entità di conversione' dei documenti archiviati). In Beautiful Soup 4, entità vengono decodificati automaticamente.

Beautiful Soup 3

>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>", 
...               convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>

Bella Zuppa 4

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>")
<html><body><p>£682m</p></body></html>

È possibile utilizzare replace_entities dalla libreria w3lib.html

In [202]: from w3lib.html import replace_entities

In [203]: replace_entities("&pound;682m")
Out[203]: u'\xa3682m'

In [204]: print replace_entities("&pound;682m")
£682m

Beautiful Soup 4 consente di impostare un formattatore alla vostra uscita

  

Se si passa formatter=None, Beautiful Soup sarà Non modificare stringhe   affatto in uscita. Questa è l'opzione più veloce, ma può portare a   Bella Zuppa di generazione non valida HTML / XML, come in questi esempi:

print(soup.prettify(formatter=None))
# <html>
#  <body>
#   <p>
#    Il a dit <<Sacré bleu!>>
#   </p>
#  </body>
# </html>

link_soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
print(link_soup.a.encode(formatter=None))
# <a href="http://example.com/?foo=val1&bar=val2">A link</a>

Questo probabilmente è neanche qui rilevante. Ma per eliminare questi entités html da un intero documento, si può fare qualcosa di simile: (Supponiamo documento = pagina e ti prego di perdonare il codice sciatta, ma se avete idee su come fare meglio, Im tutte le orecchie - Im nuovo a questo).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top