You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

273 lines
10 KiB

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