encoding.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # -*- coding: utf-8 -*-
  2. """
  3. Functions for handling encoding of web pages
  4. """
  5. import re, codecs, encodings
  6. _HEADER_ENCODING_RE = re.compile(r'charset=([\w-]+)', re.I)
  7. def http_content_type_encoding(content_type):
  8. """Extract the encoding in the content-type header
  9. >>> import w3lib.encoding
  10. >>> w3lib.encoding.http_content_type_encoding("Content-Type: text/html; charset=ISO-8859-4")
  11. 'iso8859-4'
  12. """
  13. if content_type:
  14. match = _HEADER_ENCODING_RE.search(content_type)
  15. if match:
  16. return resolve_encoding(match.group(1))
  17. # regexp for parsing HTTP meta tags
  18. _TEMPLATE = r'''%s\s*=\s*["']?\s*%s\s*["']?'''
  19. _SKIP_ATTRS = '''(?x)(?:\\s+
  20. [^=<>/\\s"'\x00-\x1f\x7f]+ # Attribute name
  21. (?:\\s*=\\s*
  22. (?: # ' and " are entity encoded (&apos;, &quot;), so no need for \', \"
  23. '[^']*' # attr in '
  24. |
  25. "[^"]*" # attr in "
  26. |
  27. [^'"\\s]+ # attr having no ' nor "
  28. ))?
  29. )*?'''
  30. _HTTPEQUIV_RE = _TEMPLATE % ('http-equiv', 'Content-Type')
  31. _CONTENT_RE = _TEMPLATE % ('content', r'(?P<mime>[^;]+);\s*charset=(?P<charset>[\w-]+)')
  32. _CONTENT2_RE = _TEMPLATE % ('charset', r'(?P<charset2>[\w-]+)')
  33. _XML_ENCODING_RE = _TEMPLATE % ('encoding', r'(?P<xmlcharset>[\w-]+)')
  34. # check for meta tags, or xml decl. and stop search if a body tag is encountered
  35. _BODY_ENCODING_PATTERN = r'<\s*(?:meta%s(?:(?:\s+%s|\s+%s){2}|\s+%s)|\?xml\s[^>]+%s|body)' % (
  36. _SKIP_ATTRS, _HTTPEQUIV_RE, _CONTENT_RE, _CONTENT2_RE, _XML_ENCODING_RE)
  37. _BODY_ENCODING_STR_RE = re.compile(_BODY_ENCODING_PATTERN, re.I)
  38. _BODY_ENCODING_BYTES_RE = re.compile(_BODY_ENCODING_PATTERN.encode('ascii'), re.I)
  39. def html_body_declared_encoding(html_body_str):
  40. '''Return the encoding specified in meta tags in the html body,
  41. or ``None`` if no suitable encoding was found
  42. >>> import w3lib.encoding
  43. >>> w3lib.encoding.html_body_declared_encoding(
  44. ... """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  45. ... "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  46. ... <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  47. ... <head>
  48. ... <title>Some title</title>
  49. ... <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  50. ... </head>
  51. ... <body>
  52. ... ...
  53. ... </body>
  54. ... </html>""")
  55. 'utf-8'
  56. >>>
  57. '''
  58. # html5 suggests the first 1024 bytes are sufficient, we allow for more
  59. chunk = html_body_str[:4096]
  60. if isinstance(chunk, bytes):
  61. match = _BODY_ENCODING_BYTES_RE.search(chunk)
  62. else:
  63. match = _BODY_ENCODING_STR_RE.search(chunk)
  64. if match:
  65. encoding = match.group('charset') or match.group('charset2') \
  66. or match.group('xmlcharset')
  67. if encoding:
  68. return resolve_encoding(encoding)
  69. # Default encoding translation
  70. # this maps cannonicalized encodings to target encodings
  71. # see http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character-encodings-0
  72. # in addition, gb18030 supercedes gb2312 & gbk
  73. # the keys are converted using _c18n_encoding and in sorted order
  74. DEFAULT_ENCODING_TRANSLATION = {
  75. 'ascii': 'cp1252',
  76. 'big5': 'big5hkscs',
  77. 'euc_kr': 'cp949',
  78. 'gb2312': 'gb18030',
  79. 'gb_2312_80': 'gb18030',
  80. 'gbk': 'gb18030',
  81. 'iso8859_11': 'cp874',
  82. 'iso8859_9': 'cp1254',
  83. 'latin_1': 'cp1252',
  84. 'macintosh': 'mac_roman',
  85. 'shift_jis': 'cp932',
  86. 'tis_620': 'cp874',
  87. 'win_1251': 'cp1251',
  88. 'windows_31j': 'cp932',
  89. 'win_31j': 'cp932',
  90. 'windows_874': 'cp874',
  91. 'win_874': 'cp874',
  92. 'x_sjis': 'cp932',
  93. 'zh_cn': 'gb18030'
  94. }
  95. def _c18n_encoding(encoding):
  96. """Cannonicalize an encoding name
  97. This performs normalization and translates aliases using python's
  98. encoding aliases
  99. """
  100. normed = encodings.normalize_encoding(encoding).lower()
  101. return encodings.aliases.aliases.get(normed, normed)
  102. def resolve_encoding(encoding_alias):
  103. """Return the encoding that `encoding_alias` maps to, or ``None``
  104. if the encoding cannot be interpreted
  105. >>> import w3lib.encoding
  106. >>> w3lib.encoding.resolve_encoding('latin1')
  107. 'cp1252'
  108. >>> w3lib.encoding.resolve_encoding('gb_2312-80')
  109. 'gb18030'
  110. >>>
  111. """
  112. c18n_encoding = _c18n_encoding(encoding_alias)
  113. translated = DEFAULT_ENCODING_TRANSLATION.get(c18n_encoding, c18n_encoding)
  114. try:
  115. return codecs.lookup(translated).name
  116. except LookupError:
  117. return None
  118. _BOM_TABLE = [
  119. (codecs.BOM_UTF32_BE, 'utf-32-be'),
  120. (codecs.BOM_UTF32_LE, 'utf-32-le'),
  121. (codecs.BOM_UTF16_BE, 'utf-16-be'),
  122. (codecs.BOM_UTF16_LE, 'utf-16-le'),
  123. (codecs.BOM_UTF8, 'utf-8')
  124. ]
  125. _FIRST_CHARS = set(c[0] for (c, _) in _BOM_TABLE)
  126. def read_bom(data):
  127. r"""Read the byte order mark in the text, if present, and
  128. return the encoding represented by the BOM and the BOM.
  129. If no BOM can be detected, ``(None, None)`` is returned.
  130. >>> import w3lib.encoding
  131. >>> w3lib.encoding.read_bom(b'\xfe\xff\x6c\x34')
  132. ('utf-16-be', '\xfe\xff')
  133. >>> w3lib.encoding.read_bom(b'\xff\xfe\x34\x6c')
  134. ('utf-16-le', '\xff\xfe')
  135. >>> w3lib.encoding.read_bom(b'\x00\x00\xfe\xff\x00\x00\x6c\x34')
  136. ('utf-32-be', '\x00\x00\xfe\xff')
  137. >>> w3lib.encoding.read_bom(b'\xff\xfe\x00\x00\x34\x6c\x00\x00')
  138. ('utf-32-le', '\xff\xfe\x00\x00')
  139. >>> w3lib.encoding.read_bom(b'\x01\x02\x03\x04')
  140. (None, None)
  141. >>>
  142. """
  143. # common case is no BOM, so this is fast
  144. if data and data[0] in _FIRST_CHARS:
  145. for bom, encoding in _BOM_TABLE:
  146. if data.startswith(bom):
  147. return encoding, bom
  148. return None, None
  149. # Python decoder doesn't follow unicode standard when handling
  150. # bad utf-8 encoded strings. see http://bugs.python.org/issue8271
  151. codecs.register_error('w3lib_replace', lambda exc: (u'\ufffd', exc.start+1))
  152. def to_unicode(data_str, encoding):
  153. """Convert a str object to unicode using the encoding given
  154. Characters that cannot be converted will be converted to ``\\ufffd`` (the
  155. unicode replacement character).
  156. """
  157. return data_str.decode(encoding, 'w3lib_replace')
  158. def html_to_unicode(content_type_header, html_body_str,
  159. default_encoding='utf8', auto_detect_fun=None):
  160. r'''Convert raw html bytes to unicode
  161. This attempts to make a reasonable guess at the content encoding of the
  162. html body, following a similar process to a web browser.
  163. It will try in order:
  164. * http content type header
  165. * BOM (byte-order mark)
  166. * meta or xml tag declarations
  167. * auto-detection, if the `auto_detect_fun` keyword argument is not ``None``
  168. * default encoding in keyword arg (which defaults to utf8)
  169. If an encoding other than the auto-detected or default encoding is used,
  170. overrides will be applied, converting some character encodings to more
  171. suitable alternatives.
  172. If a BOM is found matching the encoding, it will be stripped.
  173. The `auto_detect_fun` argument can be used to pass a function that will
  174. sniff the encoding of the text. This function must take the raw text as an
  175. argument and return the name of an encoding that python can process, or
  176. None. To use chardet, for example, you can define the function as::
  177. auto_detect_fun=lambda x: chardet.detect(x).get('encoding')
  178. or to use UnicodeDammit (shipped with the BeautifulSoup library)::
  179. auto_detect_fun=lambda x: UnicodeDammit(x).originalEncoding
  180. If the locale of the website or user language preference is known, then a
  181. better default encoding can be supplied.
  182. If `content_type_header` is not present, ``None`` can be passed signifying
  183. that the header was not present.
  184. This method will not fail, if characters cannot be converted to unicode,
  185. ``\\ufffd`` (the unicode replacement character) will be inserted instead.
  186. Returns a tuple of ``(<encoding used>, <unicode_string>)``
  187. Examples:
  188. >>> import w3lib.encoding
  189. >>> w3lib.encoding.html_to_unicode(None,
  190. ... b"""<!DOCTYPE html>
  191. ... <head>
  192. ... <meta charset="UTF-8" />
  193. ... <meta name="viewport" content="width=device-width" />
  194. ... <title>Creative Commons France</title>
  195. ... <link rel='canonical' href='http://creativecommons.fr/' />
  196. ... <body>
  197. ... <p>Creative Commons est une organisation \xc3\xa0 but non lucratif
  198. ... qui a pour dessein de faciliter la diffusion et le partage des oeuvres
  199. ... tout en accompagnant les nouvelles pratiques de cr\xc3\xa9ation \xc3\xa0 l\xe2\x80\x99\xc3\xa8re numerique.</p>
  200. ... </body>
  201. ... </html>""")
  202. ('utf-8', u'<!DOCTYPE html>\n<head>\n<meta charset="UTF-8" />\n<meta name="viewport" content="width=device-width" />\n<title>Creative Commons France</title>\n<link rel=\'canonical\' href=\'http://creativecommons.fr/\' />\n<body>\n<p>Creative Commons est une organisation \xe0 but non lucratif\nqui a pour dessein de faciliter la diffusion et le partage des oeuvres\ntout en accompagnant les nouvelles pratiques de cr\xe9ation \xe0 l\u2019\xe8re numerique.</p>\n</body>\n</html>')
  203. >>>
  204. '''
  205. enc = http_content_type_encoding(content_type_header)
  206. bom_enc, bom = read_bom(html_body_str)
  207. if enc is not None:
  208. # remove BOM if it agrees with the encoding
  209. if enc == bom_enc:
  210. html_body_str = html_body_str[len(bom):]
  211. elif enc == 'utf-16' or enc == 'utf-32':
  212. # read endianness from BOM, or default to big endian
  213. # tools.ietf.org/html/rfc2781 section 4.3
  214. if bom_enc is not None and bom_enc.startswith(enc):
  215. enc = bom_enc
  216. html_body_str = html_body_str[len(bom):]
  217. else:
  218. enc += '-be'
  219. return enc, to_unicode(html_body_str, enc)
  220. if bom_enc is not None:
  221. return bom_enc, to_unicode(html_body_str[len(bom):], bom_enc)
  222. enc = html_body_declared_encoding(html_body_str)
  223. if enc is None and (auto_detect_fun is not None):
  224. enc = auto_detect_fun(html_body_str)
  225. if enc is None:
  226. enc = default_encoding
  227. return enc, to_unicode(html_body_str, enc)