Pergunta

Essa pergunta já tem resposta aqui:

Estou fazendo alguns web scraping e os sites freqüentemente usam entidades HTML para representar caracteres não ASCII.O Python possui um utilitário que pega uma string com entidades HTML e retorna um tipo unicode?

Por exemplo:

Eu voltei:

ǎ

que representa um "ǎ" com uma marca de tom.Em binário, isso é representado como 01ce de 16 bits.Quero converter a entidade html em valor u'\u01ce'

Foi útil?

Solução

O próprio HTMLParser da biblioteca padrão tem uma função não documentada unescape() que faz exatamente o que você pensa que faz:

import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'

Outras dicas

Python tem o htmlentitydefs módulo, mas isso não inclui uma função para remover o escape de entidades HTML.

O desenvolvedor Python Fredrik Lundh (autor de elementtree, entre outras coisas) tem essa função em seu site, que funciona com entidades decimais, hexadecimais e nomeadas:

import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

Use o integrado unichr -- BeautifulSoup não é necessário:

>>> entity = '&#x01ce'
>>> unichr(int(entity[3:],16))
u'\u01ce'

Uma alternativa, se você tiver lxml:

>>> import lxml.html
>>> lxml.html.fromstring('&#x01ce').text
u'\u01ce'

Se você estiver no Python 3.4 ou mais recente, você pode simplesmente usar o html.unescape:

import html

s = html.unescape(s)

Você pode encontrar uma resposta aqui - Obtendo caracteres internacionais de uma página da web?

EDITAR:Parece que BeautifulSoup não converte entidades escritas em formato hexadecimal.Pode ser corrigido:

import copy, re
from BeautifulSoup import BeautifulSoup

hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'), 
                     lambda m: '&#%d;' % int(m.group(1), 16))]

def convert(html):
    return BeautifulSoup(html,
        convertEntities=BeautifulSoup.HTML_ENTITIES,
        markupMassage=hexentityMassage).contents[0].string

html = '<html>&#x01ce;&#462;</html>'
print repr(convert(html))
# u'\u01ce\u01ce'

EDITAR:

unescape() função mencionada por @dF que usa htmlentitydefs módulo padrão e unichr() pode ser mais apropriado neste caso.

Esta é uma função que deve ajudá-lo a acertar e converter entidades de volta para caracteres utf-8.

def unescape(text):
   """Removes HTML or XML character references 
      and entities from a text string.
   @param text The HTML (or XML) source text.
   @return The plain text, as a Unicode string, if necessary.
   from Fredrik Lundh
   2008-01-03: input only unicode characters string.
   http://effbot.org/zone/re-sub.htm#unescape-html
   """
   def fixup(m):
      text = m.group(0)
      if text[:2] == "&#":
         # character reference
         try:
            if text[:3] == "&#x":
               return unichr(int(text[3:-1], 16))
            else:
               return unichr(int(text[2:-1]))
         except ValueError:
            print "Value Error"
            pass
      else:
         # named entity
         # reescape the reserved characters.
         try:
            if text[1:-1] == "amp":
               text = "&amp;amp;"
            elif text[1:-1] == "gt":
               text = "&amp;gt;"
            elif text[1:-1] == "lt":
               text = "&amp;lt;"
            else:
               print text[1:-1]
               text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
         except KeyError:
            print "keyerror"
            pass
      return text # leave as is
   return re.sub("&#?\w+;", fixup, text)

Não sei por que o thread de transbordamento de pilha não inclui o ';' Na pesquisa/substituição (ou seja,lambda m:'&#%d*;*') Caso contrário, BeautifulSoup poderá vomitar porque o caractere adjacente pode ser interpretado como parte do código HTML (ou seja,&#39B para &#39Blecaute).

Isso funcionou melhor para mim:

import re
from BeautifulSoup import BeautifulSoup

html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">&#x27;Blackout in a can; on some shelves despite ban</a>'

hexentityMassage = [(re.compile('&#x([^;]+);'), 
lambda m: '&#%d;' % int(m.group(1), 16))]

soup = BeautifulSoup(html_string, 
convertEntities=BeautifulSoup.HTML_ENTITIES, 
markupMassage=hexentityMassage)
  1. O int(m.group(1), 16) converte o formato do número (especificado na base 16) de volta para um número inteiro.
  2. m.group(0) retorna a correspondência inteira, m.group(1) retorna o grupo de captura regexp
  3. Basicamente, usar markupMessage é o mesmo que:
    html_string = re.sub('&#x([^;]+);', lambda m:'&#%d;' % int (M.Group (1), 16), html_string)

Outra solução é a biblioteca integrada xml.sax.saxutils (tanto para html quanto para xml).No entanto, ele converterá apenas &gt, &amp e &lt.

from xml.sax.saxutils import unescape

escaped_text = unescape(text_to_escape)

Aqui está a versão Python 3 do resposta do dF:

import re
import html.entities

def unescape(text):
    """
    Removes HTML or XML character references and entities from a text string.

    :param text:    The HTML (or XML) source text.
    :return:        The plain text, as a Unicode string, if necessary.
    """
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return chr(int(text[3:-1], 16))
                else:
                    return chr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = chr(html.entities.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

As principais mudanças dizem respeito htmlentitydefs isso é agora html.entities e unichr isso é agora chr.Veja isso Guia de portabilidade do Python 3.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top