문제

이 질문에는 이미 답변이 있습니다.

나는 일부 웹 스크래핑을 수행하고 있으며 사이트에서는 ASCII가 아닌 문자를 나타내기 위해 HTML 엔터티를 자주 사용합니다.Python에는 HTML 엔터티가 포함된 문자열을 가져와 유니코드 유형을 반환하는 유틸리티가 있습니까?

예를 들어:

난 돌아가 겠어:

ǎ

성조 표시가 있는 "Ď"를 나타냅니다.바이너리에서는 16비트 01ce로 표시됩니다.HTML 엔터티를 값으로 변환하고 싶습니다 u'\u01ce'

도움이 되었습니까?

해결책

표준 lib의 자체 HTMLParser에는 문서화되지 않은 함수 unescape()가 있는데, 이 함수는 여러분이 생각하는 것과 정확히 일치합니다.

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

다른 팁

파이썬은 htmlentitydefs 모듈이지만 여기에는 HTML 엔터티를 이스케이프 해제하는 기능이 포함되어 있지 않습니다.

Python 개발자 Fredrik Lundh(elementtree의 저자 등)는 이러한 기능을 가지고 있습니다. 그의 웹사이트에서, 이는 10진수, 16진수 및 명명된 엔터티와 함께 ​​작동합니다.

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)

내장을 사용하세요 unichr -- BeautifulSoup는 필요하지 않습니다.

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

lxml이 있는 경우 대안:

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

Python 3.4 이상을 사용하는 경우 간단히 다음을 사용할 수 있습니다. html.unescape:

import html

s = html.unescape(s)

여기서 답을 찾을 수 있습니다. 웹 페이지에서 국제 문자를 얻으시겠습니까?

편집하다:그것은 것 같다 BeautifulSoup 16진수 형식으로 작성된 엔터티를 변환하지 않습니다.다음과 같이 수정될 수 있습니다.

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'

편집하다:

unescape() 언급된 기능 @dF 사용하는 htmlentitydefs 표준 모듈 및 unichr() 이 경우에는 더 적합할 수 있습니다.

이것은 올바른 결과를 얻고 엔터티를 다시 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)

스택 오버플로 스레드에 왜 ';'가 포함되지 않는 이유는 확실하지 않습니다. 검색/교체에서 (즉람다 m:'&#%디*;*') 그렇지 않으면 인접한 문자가 HTML 코드의 일부로 해석될 수 있기 때문에 BeautifulSoup이 소리를 낼 수 있습니다(예:&#39B는 &#39정전)입니다.

이것은 나에게 더 효과적이었습니다.

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. int(m.group(1), 16)은 숫자(16진법으로 지정됨) 형식을 다시 정수로 변환합니다.
  2. m.group(0)은 전체 일치 항목을 반환하고, m.group(1)은 정규 표현식 캡처 그룹을 반환합니다.
  3. 기본적으로 markupMessage를 사용하는 것은 다음과 같습니다.
    html_string = re.sub('&#x([^;]+);', 람다 m:'&#%디;' % int (m.group (1), 16), html_string)

또 다른 해결책은 내장 라이브러리 xml.sax.saxutils(html 및 xml 모두용)입니다.그러나 &gt, &amp 및 &lt만 변환됩니다.

from xml.sax.saxutils import unescape

escaped_text = unescape(text_to_escape)

다음은 Python 3 버전입니다. 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)

주요 변경 사항 htmlentitydefs 그게 지금이야 html.entities 그리고 unichr 그게 지금이야 chr.이것 좀 봐 Python 3 포팅 ​​가이드.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top