Decodifica entità HTML nella stringa Python?
-
21-09-2019 - |
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>£682m</p>")
>>> text = soup.find("p").string
>>> print text
£682m
Come faccio a decodificare le entità HTML in text
per ottenere "£682m"
invece di "£682m"
.
Soluzione
Python 3.4 +
import html
print(html.unescape('£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:
- Per Python 2,6-2,7 è nel
HTMLParser
- Per Python 3 è nel
html.parser
>>> try:
... # Python 2.6-2.7
... from HTMLParser import HTMLParser
... except ImportError:
... # Python 3
... from html.parser import HTMLParser
...
>>> h = HTMLParser()
>>> print(h.unescape('£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('£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>£682m</p>",
... convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>
Bella Zuppa 4
>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>£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("£682m")
Out[203]: u'\xa3682m'
In [204]: print replace_entities("£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