url.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. """
  2. This module contains general purpose URL functions not found in the standard
  3. library.
  4. """
  5. import base64
  6. import codecs
  7. import os
  8. import re
  9. import posixpath
  10. import warnings
  11. import six
  12. from collections import namedtuple
  13. from six.moves.urllib.parse import (urljoin, urlsplit, urlunsplit,
  14. urldefrag, urlencode, urlparse,
  15. quote, parse_qs, parse_qsl,
  16. ParseResult, unquote, urlunparse)
  17. from six.moves.urllib.request import pathname2url, url2pathname
  18. from w3lib.util import to_bytes, to_native_str, to_unicode
  19. # error handling function for bytes-to-Unicode decoding errors with URLs
  20. def _quote_byte(error):
  21. return (to_unicode(quote(error.object[error.start:error.end])), error.end)
  22. codecs.register_error('percentencode', _quote_byte)
  23. # Python 2.x urllib.always_safe become private in Python 3.x;
  24. # its content is copied here
  25. _ALWAYS_SAFE_BYTES = (b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  26. b'abcdefghijklmnopqrstuvwxyz'
  27. b'0123456789' b'_.-')
  28. def urljoin_rfc(base, ref, encoding='utf-8'):
  29. r"""
  30. .. warning::
  31. This function is deprecated and will be removed in future.
  32. It is not supported with Python 3.
  33. Please use ``urlparse.urljoin`` instead.
  34. Same as urlparse.urljoin but supports unicode values in base and ref
  35. parameters (in which case they will be converted to str using the given
  36. encoding).
  37. Always returns a str.
  38. >>> import w3lib.url
  39. >>> w3lib.url.urljoin_rfc('http://www.example.com/path/index.html', u'/otherpath/index2.html')
  40. 'http://www.example.com/otherpath/index2.html'
  41. >>>
  42. >>> # Note: the following does not work in Python 3
  43. >>> w3lib.url.urljoin_rfc(b'http://www.example.com/path/index.html', u'fran\u00e7ais/d\u00e9part.htm') # doctest: +SKIP
  44. 'http://www.example.com/path/fran\xc3\xa7ais/d\xc3\xa9part.htm'
  45. >>>
  46. """
  47. warnings.warn("w3lib.url.urljoin_rfc is deprecated, use urlparse.urljoin instead",
  48. DeprecationWarning)
  49. str_base = to_bytes(base, encoding)
  50. str_ref = to_bytes(ref, encoding)
  51. return urljoin(str_base, str_ref)
  52. _reserved = b';/?:@&=+$|,#' # RFC 3986 (Generic Syntax)
  53. _unreserved_marks = b"-_.!~*'()" # RFC 3986 sec 2.3
  54. _safe_chars = _ALWAYS_SAFE_BYTES + b'%' + _reserved + _unreserved_marks
  55. def safe_url_string(url, encoding='utf8', path_encoding='utf8'):
  56. """Convert the given URL into a legal URL by escaping unsafe characters
  57. according to RFC-3986.
  58. If a bytes URL is given, it is first converted to `str` using the given
  59. encoding (which defaults to 'utf-8'). 'utf-8' encoding is used for
  60. URL path component (unless overriden by path_encoding), and given
  61. encoding is used for query string or form data.
  62. When passing an encoding, you should use the encoding of the
  63. original page (the page from which the URL was extracted from).
  64. Calling this function on an already "safe" URL will return the URL
  65. unmodified.
  66. Always returns a native `str` (bytes in Python2, unicode in Python3).
  67. """
  68. # Python3's urlsplit() chokes on bytes input with non-ASCII chars,
  69. # so let's decode (to Unicode) using page encoding:
  70. # - it is assumed that a raw bytes input comes from a document
  71. # encoded with the supplied encoding (or UTF8 by default)
  72. # - if the supplied (or default) encoding chokes,
  73. # percent-encode offending bytes
  74. parts = urlsplit(to_unicode(url, encoding=encoding,
  75. errors='percentencode'))
  76. # IDNA encoding can fail for too long labels (>63 characters)
  77. # or missing labels (e.g. http://.example.com)
  78. try:
  79. netloc = parts.netloc.encode('idna')
  80. except UnicodeError:
  81. netloc = parts.netloc
  82. # quote() in Python2 return type follows input type;
  83. # quote() in Python3 always returns Unicode (native str)
  84. return urlunsplit((
  85. to_native_str(parts.scheme),
  86. to_native_str(netloc).rstrip(':'),
  87. # default encoding for path component SHOULD be UTF-8
  88. quote(to_bytes(parts.path, path_encoding), _safe_chars),
  89. # encoding of query and fragment follows page encoding
  90. # or form-charset (if known and passed)
  91. quote(to_bytes(parts.query, encoding), _safe_chars),
  92. quote(to_bytes(parts.fragment, encoding), _safe_chars),
  93. ))
  94. _parent_dirs = re.compile(r'/?(\.\./)+')
  95. def safe_download_url(url):
  96. """ Make a url for download. This will call safe_url_string
  97. and then strip the fragment, if one exists. The path will
  98. be normalised.
  99. If the path is outside the document root, it will be changed
  100. to be within the document root.
  101. """
  102. safe_url = safe_url_string(url)
  103. scheme, netloc, path, query, _ = urlsplit(safe_url)
  104. if path:
  105. path = _parent_dirs.sub('', posixpath.normpath(path))
  106. if url.endswith('/') and not path.endswith('/'):
  107. path += '/'
  108. else:
  109. path = '/'
  110. return urlunsplit((scheme, netloc, path, query, ''))
  111. def is_url(text):
  112. return text.partition("://")[0] in ('file', 'http', 'https')
  113. def url_query_parameter(url, parameter, default=None, keep_blank_values=0):
  114. """Return the value of a url parameter, given the url and parameter name
  115. General case:
  116. >>> import w3lib.url
  117. >>> w3lib.url.url_query_parameter("product.html?id=200&foo=bar", "id")
  118. '200'
  119. >>>
  120. Return a default value if the parameter is not found:
  121. >>> w3lib.url.url_query_parameter("product.html?id=200&foo=bar", "notthere", "mydefault")
  122. 'mydefault'
  123. >>>
  124. Returns None if `keep_blank_values` not set or 0 (default):
  125. >>> w3lib.url.url_query_parameter("product.html?id=", "id")
  126. >>>
  127. Returns an empty string if `keep_blank_values` set to 1:
  128. >>> w3lib.url.url_query_parameter("product.html?id=", "id", keep_blank_values=1)
  129. ''
  130. >>>
  131. """
  132. queryparams = parse_qs(
  133. urlsplit(str(url))[3],
  134. keep_blank_values=keep_blank_values
  135. )
  136. return queryparams.get(parameter, [default])[0]
  137. def url_query_cleaner(url, parameterlist=(), sep='&', kvsep='=', remove=False, unique=True, keep_fragments=False):
  138. """Clean URL arguments leaving only those passed in the parameterlist keeping order
  139. >>> import w3lib.url
  140. >>> w3lib.url.url_query_cleaner("product.html?id=200&foo=bar&name=wired", ('id',))
  141. 'product.html?id=200'
  142. >>> w3lib.url.url_query_cleaner("product.html?id=200&foo=bar&name=wired", ['id', 'name'])
  143. 'product.html?id=200&name=wired'
  144. >>>
  145. If `unique` is ``False``, do not remove duplicated keys
  146. >>> w3lib.url.url_query_cleaner("product.html?d=1&e=b&d=2&d=3&other=other", ['d'], unique=False)
  147. 'product.html?d=1&d=2&d=3'
  148. >>>
  149. If `remove` is ``True``, leave only those **not in parameterlist**.
  150. >>> w3lib.url.url_query_cleaner("product.html?id=200&foo=bar&name=wired", ['id'], remove=True)
  151. 'product.html?foo=bar&name=wired'
  152. >>> w3lib.url.url_query_cleaner("product.html?id=2&foo=bar&name=wired", ['id', 'foo'], remove=True)
  153. 'product.html?name=wired'
  154. >>>
  155. By default, URL fragments are removed. If you need to preserve fragments,
  156. pass the ``keep_fragments`` argument as ``True``.
  157. >>> w3lib.url.url_query_cleaner('http://domain.tld/?bla=123#123123', ['bla'], remove=True, keep_fragments=True)
  158. 'http://domain.tld/#123123'
  159. """
  160. if isinstance(parameterlist, (six.text_type, bytes)):
  161. parameterlist = [parameterlist]
  162. url, fragment = urldefrag(url)
  163. base, _, query = url.partition('?')
  164. seen = set()
  165. querylist = []
  166. for ksv in query.split(sep):
  167. k, _, _ = ksv.partition(kvsep)
  168. if unique and k in seen:
  169. continue
  170. elif remove and k in parameterlist:
  171. continue
  172. elif not remove and k not in parameterlist:
  173. continue
  174. else:
  175. querylist.append(ksv)
  176. seen.add(k)
  177. url = '?'.join([base, sep.join(querylist)]) if querylist else base
  178. if keep_fragments:
  179. url += '#' + fragment
  180. return url
  181. def add_or_replace_parameter(url, name, new_value):
  182. """Add or remove a parameter to a given url
  183. >>> import w3lib.url
  184. >>> w3lib.url.add_or_replace_parameter('http://www.example.com/index.php', 'arg', 'v')
  185. 'http://www.example.com/index.php?arg=v'
  186. >>> w3lib.url.add_or_replace_parameter('http://www.example.com/index.php?arg1=v1&arg2=v2&arg3=v3', 'arg4', 'v4')
  187. 'http://www.example.com/index.php?arg1=v1&arg2=v2&arg3=v3&arg4=v4'
  188. >>> w3lib.url.add_or_replace_parameter('http://www.example.com/index.php?arg1=v1&arg2=v2&arg3=v3', 'arg3', 'v3new')
  189. 'http://www.example.com/index.php?arg1=v1&arg2=v2&arg3=v3new'
  190. >>>
  191. """
  192. parsed = urlsplit(url)
  193. args = parse_qsl(parsed.query, keep_blank_values=True)
  194. new_args = []
  195. found = False
  196. for name_, value_ in args:
  197. if name_ == name:
  198. new_args.append((name_, new_value))
  199. found = True
  200. else:
  201. new_args.append((name_, value_))
  202. if not found:
  203. new_args.append((name, new_value))
  204. query = urlencode(new_args)
  205. return urlunsplit(parsed._replace(query=query))
  206. def path_to_file_uri(path):
  207. """Convert local filesystem path to legal File URIs as described in:
  208. http://en.wikipedia.org/wiki/File_URI_scheme
  209. """
  210. x = pathname2url(os.path.abspath(path))
  211. if os.name == 'nt':
  212. x = x.replace('|', ':') # http://bugs.python.org/issue5861
  213. return 'file:///%s' % x.lstrip('/')
  214. def file_uri_to_path(uri):
  215. """Convert File URI to local filesystem path according to:
  216. http://en.wikipedia.org/wiki/File_URI_scheme
  217. """
  218. uri_path = urlparse(uri).path
  219. return url2pathname(uri_path)
  220. def any_to_uri(uri_or_path):
  221. """If given a path name, return its File URI, otherwise return it
  222. unmodified
  223. """
  224. if os.path.splitdrive(uri_or_path)[0]:
  225. return path_to_file_uri(uri_or_path)
  226. u = urlparse(uri_or_path)
  227. return uri_or_path if u.scheme else path_to_file_uri(uri_or_path)
  228. # ASCII characters.
  229. _char = set(map(chr, range(127)))
  230. # RFC 2045 token.
  231. _token = r'[{}]+'.format(re.escape(''.join(_char -
  232. # Control characters.
  233. set(map(chr, range(0, 32))) -
  234. # tspecials and space.
  235. set('()<>@,;:\\"/[]?= '))))
  236. # RFC 822 quoted-string, without surrounding quotation marks.
  237. _quoted_string = r'(?:[{}]|(?:\\[{}]))*'.format(
  238. re.escape(''.join(_char - {'"', '\\', '\r'})),
  239. re.escape(''.join(_char))
  240. )
  241. # Encode the regular expression strings to make them into bytes, as Python 3
  242. # bytes have no format() method, but bytes must be passed to re.compile() in
  243. # order to make a pattern object that can be used to match on bytes.
  244. # RFC 2397 mediatype.
  245. _mediatype_pattern = re.compile(
  246. r'{token}/{token}'.format(token=_token).encode()
  247. )
  248. _mediatype_parameter_pattern = re.compile(
  249. r';({token})=(?:({token})|"({quoted})")'.format(token=_token,
  250. quoted=_quoted_string
  251. ).encode()
  252. )
  253. _ParseDataURIResult = namedtuple("ParseDataURIResult",
  254. "media_type media_type_parameters data")
  255. def parse_data_uri(uri):
  256. """
  257. Parse a data: URI, returning a 3-tuple of media type, dictionary of media
  258. type parameters, and data.
  259. """
  260. if not isinstance(uri, bytes):
  261. uri = safe_url_string(uri).encode('ascii')
  262. try:
  263. scheme, uri = uri.split(b':', 1)
  264. except ValueError:
  265. raise ValueError("invalid URI")
  266. if scheme.lower() != b'data':
  267. raise ValueError("not a data URI")
  268. # RFC 3986 section 2.1 allows percent encoding to escape characters that
  269. # would be interpreted as delimiters, implying that actual delimiters
  270. # should not be percent-encoded.
  271. # Decoding before parsing will allow malformed URIs with percent-encoded
  272. # delimiters, but it makes parsing easier and should not affect
  273. # well-formed URIs, as the delimiters used in this URI scheme are not
  274. # allowed, percent-encoded or not, in tokens.
  275. if six.PY2:
  276. uri = unquote(uri)
  277. else:
  278. uri = unquote_to_bytes(uri)
  279. media_type = "text/plain"
  280. media_type_params = {}
  281. m = _mediatype_pattern.match(uri)
  282. if m:
  283. media_type = m.group().decode()
  284. uri = uri[m.end():]
  285. else:
  286. media_type_params['charset'] = "US-ASCII"
  287. while True:
  288. m = _mediatype_parameter_pattern.match(uri)
  289. if m:
  290. attribute, value, value_quoted = m.groups()
  291. if value_quoted:
  292. value = re.sub(br'\\(.)', r'\1', value_quoted)
  293. media_type_params[attribute.decode()] = value.decode()
  294. uri = uri[m.end():]
  295. else:
  296. break
  297. try:
  298. is_base64, data = uri.split(b',', 1)
  299. except ValueError:
  300. raise ValueError("invalid data URI")
  301. if is_base64:
  302. if is_base64 != b";base64":
  303. raise ValueError("invalid data URI")
  304. data = base64.b64decode(data)
  305. return _ParseDataURIResult(media_type, media_type_params, data)
  306. __all__ = ["add_or_replace_parameter",
  307. "any_to_uri",
  308. "canonicalize_url",
  309. "file_uri_to_path",
  310. "is_url",
  311. "parse_data_uri",
  312. "path_to_file_uri",
  313. "safe_download_url",
  314. "safe_url_string",
  315. "url_query_cleaner",
  316. "url_query_parameter",
  317. # this last one is deprecated ; include it to be on the safe side
  318. "urljoin_rfc"]
  319. def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
  320. # IDNA encoding can fail for too long labels (>63 characters)
  321. # or missing labels (e.g. http://.example.com)
  322. try:
  323. netloc = parts.netloc.encode('idna')
  324. except UnicodeError:
  325. netloc = parts.netloc
  326. return (
  327. to_native_str(parts.scheme),
  328. to_native_str(netloc),
  329. # default encoding for path component SHOULD be UTF-8
  330. quote(to_bytes(parts.path, path_encoding), _safe_chars),
  331. quote(to_bytes(parts.params, path_encoding), _safe_chars),
  332. # encoding of query and fragment follows page encoding
  333. # or form-charset (if known and passed)
  334. quote(to_bytes(parts.query, encoding), _safe_chars),
  335. quote(to_bytes(parts.fragment, encoding), _safe_chars)
  336. )
  337. def canonicalize_url(url, keep_blank_values=True, keep_fragments=False,
  338. encoding=None):
  339. r"""Canonicalize the given url by applying the following procedures:
  340. - sort query arguments, first by key, then by value
  341. - percent encode paths ; non-ASCII characters are percent-encoded
  342. using UTF-8 (RFC-3986)
  343. - percent encode query arguments ; non-ASCII characters are percent-encoded
  344. using passed `encoding` (UTF-8 by default)
  345. - normalize all spaces (in query arguments) '+' (plus symbol)
  346. - normalize percent encodings case (%2f -> %2F)
  347. - remove query arguments with blank values (unless `keep_blank_values` is True)
  348. - remove fragments (unless `keep_fragments` is True)
  349. The url passed can be bytes or unicode, while the url returned is
  350. always a native str (bytes in Python 2, unicode in Python 3).
  351. >>> import w3lib.url
  352. >>>
  353. >>> # sorting query arguments
  354. >>> w3lib.url.canonicalize_url('http://www.example.com/do?c=3&b=5&b=2&a=50')
  355. 'http://www.example.com/do?a=50&b=2&b=5&c=3'
  356. >>>
  357. >>> # UTF-8 conversion + percent-encoding of non-ASCII characters
  358. >>> w3lib.url.canonicalize_url(u'http://www.example.com/r\u00e9sum\u00e9')
  359. 'http://www.example.com/r%C3%A9sum%C3%A9'
  360. >>>
  361. For more examples, see the tests in `tests/test_url.py`.
  362. """
  363. # If supplied `encoding` is not compatible with all characters in `url`,
  364. # fallback to UTF-8 as safety net.
  365. # UTF-8 can handle all Unicode characters,
  366. # so we should be covered regarding URL normalization,
  367. # if not for proper URL expected by remote website.
  368. try:
  369. scheme, netloc, path, params, query, fragment = _safe_ParseResult(
  370. parse_url(url), encoding=encoding)
  371. except UnicodeEncodeError as e:
  372. scheme, netloc, path, params, query, fragment = _safe_ParseResult(
  373. parse_url(url), encoding='utf8')
  374. # 1. decode query-string as UTF-8 (or keep raw bytes),
  375. # sort values,
  376. # and percent-encode them back
  377. if six.PY2:
  378. keyvals = parse_qsl(query, keep_blank_values)
  379. else:
  380. # Python3's urllib.parse.parse_qsl does not work as wanted
  381. # for percent-encoded characters that do not match passed encoding,
  382. # they get lost.
  383. #
  384. # e.g., 'q=b%a3' becomes [('q', 'b\ufffd')]
  385. # (ie. with 'REPLACEMENT CHARACTER' (U+FFFD),
  386. # instead of \xa3 that you get with Python2's parse_qsl)
  387. #
  388. # what we want here is to keep raw bytes, and percent encode them
  389. # so as to preserve whatever encoding what originally used.
  390. #
  391. # See https://tools.ietf.org/html/rfc3987#section-6.4:
  392. #
  393. # For example, it is possible to have a URI reference of
  394. # "http://www.example.org/r%E9sum%E9.xml#r%C3%A9sum%C3%A9", where the
  395. # document name is encoded in iso-8859-1 based on server settings, but
  396. # where the fragment identifier is encoded in UTF-8 according to
  397. # [XPointer]. The IRI corresponding to the above URI would be (in XML
  398. # notation)
  399. # "http://www.example.org/r%E9sum%E9.xml#r&#xE9;sum&#xE9;".
  400. # Similar considerations apply to query parts. The functionality of
  401. # IRIs (namely, to be able to include non-ASCII characters) can only be
  402. # used if the query part is encoded in UTF-8.
  403. keyvals = parse_qsl_to_bytes(query, keep_blank_values)
  404. keyvals.sort()
  405. query = urlencode(keyvals)
  406. # 2. decode percent-encoded sequences in path as UTF-8 (or keep raw bytes)
  407. # and percent-encode path again (this normalizes to upper-case %XX)
  408. uqp = _unquotepath(path)
  409. path = quote(uqp, _safe_chars) or '/'
  410. fragment = '' if not keep_fragments else fragment
  411. # every part should be safe already
  412. return urlunparse((scheme,
  413. netloc.lower().rstrip(':'),
  414. path,
  415. params,
  416. query,
  417. fragment))
  418. def _unquotepath(path):
  419. for reserved in ('2f', '2F', '3f', '3F'):
  420. path = path.replace('%' + reserved, '%25' + reserved.upper())
  421. if six.PY2:
  422. # in Python 2, '%a3' becomes '\xa3', which is what we want
  423. return unquote(path)
  424. else:
  425. # in Python 3,
  426. # standard lib's unquote() does not work for non-UTF-8
  427. # percent-escaped characters, they get lost.
  428. # e.g., '%a3' becomes 'REPLACEMENT CHARACTER' (U+FFFD)
  429. #
  430. # unquote_to_bytes() returns raw bytes instead
  431. return unquote_to_bytes(path)
  432. def parse_url(url, encoding=None):
  433. """Return urlparsed url from the given argument (which could be an already
  434. parsed url)
  435. """
  436. if isinstance(url, ParseResult):
  437. return url
  438. return urlparse(to_unicode(url, encoding))
  439. if not six.PY2:
  440. from urllib.parse import _coerce_args, unquote_to_bytes
  441. def parse_qsl_to_bytes(qs, keep_blank_values=False):
  442. """Parse a query given as a string argument.
  443. Data are returned as a list of name, value pairs as bytes.
  444. Arguments:
  445. qs: percent-encoded query string to be parsed
  446. keep_blank_values: flag indicating whether blank values in
  447. percent-encoded queries should be treated as blank strings. A
  448. true value indicates that blanks should be retained as blank
  449. strings. The default false value indicates that blank values
  450. are to be ignored and treated as if they were not included.
  451. """
  452. # This code is the same as Python3's parse_qsl()
  453. # (at https://hg.python.org/cpython/rev/c38ac7ab8d9a)
  454. # except for the unquote(s, encoding, errors) calls replaced
  455. # with unquote_to_bytes(s)
  456. qs, _coerce_result = _coerce_args(qs)
  457. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  458. r = []
  459. for name_value in pairs:
  460. if not name_value:
  461. continue
  462. nv = name_value.split('=', 1)
  463. if len(nv) != 2:
  464. # Handle case of a control-name with no equal sign
  465. if keep_blank_values:
  466. nv.append('')
  467. else:
  468. continue
  469. if len(nv[1]) or keep_blank_values:
  470. name = nv[0].replace('+', ' ')
  471. name = unquote_to_bytes(name)
  472. name = _coerce_result(name)
  473. value = nv[1].replace('+', ' ')
  474. value = unquote_to_bytes(value)
  475. value = _coerce_result(value)
  476. r.append((name, value))
  477. return r