pax_global_header00006660000000000000000000000064152571576770014540gustar00rootroot0000000000000052 comment=537c5d46455ae8b2c67b53fc03b36ef1da8c4837 scrapy-w3lib-d6b4a87/000077500000000000000000000000001525715767700145005ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/.git-blame-ignore-revs000066400000000000000000000002071525715767700205770ustar00rootroot00000000000000# This is a list of commits that git blame should ignore # running pre-commit on all the code 47be6dd35faf78f06b6183ea9dad6b5f78f5c756 scrapy-w3lib-d6b4a87/.github/000077500000000000000000000000001525715767700160405ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/.github/dependabot.yml000066400000000000000000000004011525715767700206630ustar00rootroot00000000000000--- version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly groups: github-actions: patterns: - '*' cooldown: default-days: 7 scrapy-w3lib-d6b4a87/.github/workflows/000077500000000000000000000000001525715767700200755ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/.github/workflows/checks.yml000066400000000000000000000030001525715767700220510ustar00rootroot00000000000000--- name: Checks permissions: contents: read on: push: branches: - master pull_request: branches: - master jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: include: # Keep in sync with .readthedocs.yml - python-version: '3.14' env: TOXENV: docs - python-version: '3.14' env: TOXENV: pre-commit - python-version: '3.14' env: TOXENV: pylint - python-version: '3.14' env: TOXENV: typing - python-version: '3.14' env: TOXENV: twinecheck steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} - name: Run check env: ${{ matrix.env }} run: | pip install --upgrade pip pip install --upgrade tox tox scrapy-w3lib-d6b4a87/.github/workflows/codspeed.yml000066400000000000000000000023151525715767700224070ustar00rootroot00000000000000--- name: codspeed on: push: branches: - master pull_request: paths: - w3lib/** - tests/benchmarks/** - .github/workflows/codspeed.yml - pyproject.toml workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true permissions: contents: read jobs: benchmark: runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python 3.13 uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.13' - name: Install dependencies run: | pip install --upgrade pip pip install --upgrade tox tox -n -e benchmark - name: Run benchmarks uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 with: mode: simulation run: tox -e benchmark scrapy-w3lib-d6b4a87/.github/workflows/publish.yml000066400000000000000000000031521525715767700222670ustar00rootroot00000000000000--- name: Publish permissions: contents: read on: push: tags: - v[0-9]+.[0-9]+.[0-9]+ jobs: build: name: Build distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.14' - name: Install pypa/build run: python3 -m pip install build --user - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: python-package-distributions path: dist/ publish: name: Publish to PyPI needs: - build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/p/w3lib permissions: id-token: write steps: - name: Download all the dists uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: python-package-distributions path: dist/ - name: Publish distribution to PyPI uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 scrapy-w3lib-d6b4a87/.github/workflows/test.yml000066400000000000000000000025201525715767700215760ustar00rootroot00000000000000--- name: Test permissions: contents: read on: push: branches: - master pull_request: branches: - master env: FORCE_COLOR: 1 jobs: tests: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: python-version: - '3.10' - '3.11' - '3.12' - '3.13' - '3.14' - '3.15' - pypy3.11 os: [windows-latest, macos-latest, ubuntu-latest] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} allow-prereleases: true - name: Run tests run: | pip install --upgrade pip pip install --upgrade tox tox -e py - name: Upload coverage report uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 scrapy-w3lib-d6b4a87/.gitignore000066400000000000000000000002561525715767700164730ustar00rootroot00000000000000*.pyc *egg-info MANIFEST .tox venv build dist docs/_build _trial_temp .coverage coverage.xml .cache .mypy_cache/ /index.txt .dmypy.json .hypothesis/ .idea/ .codspeed uv.lock scrapy-w3lib-d6b4a87/.pre-commit-config.yaml000066400000000000000000000023661525715767700207700ustar00rootroot00000000000000--- exclude: ^tests/benchmarks/pages/ repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.15.12 hooks: - id: ruff-check args: [--fix] - id: ruff-format - repo: https://github.com/adamchainz/blacken-docs rev: 1.20.0 hooks: - id: blacken-docs additional_dependencies: - black==26.1.0 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/sphinx-contrib/sphinx-lint rev: v1.0.2 hooks: - id: sphinx-lint - repo: https://github.com/adrienverge/yamllint.git rev: v1.38.0 hooks: - id: yamllint args: [--format, parsable, --strict, -d, '{rules: {truthy: {check-keys: false}}}'] - repo: https://github.com/jumanjihouse/pre-commit-hook-yamlfmt rev: 0.2.3 hooks: - id: yamlfmt - repo: https://github.com/rhysd/actionlint rev: v1.7.12 hooks: - id: actionlint - repo: https://github.com/zizmorcore/zizmor-pre-commit rev: v1.29.0 hooks: - id: zizmor args: [--no-progress, --fix] scrapy-w3lib-d6b4a87/.readthedocs.yml000066400000000000000000000006411525715767700175670ustar00rootroot00000000000000--- version: 2 formats: all sphinx: configuration: docs/conf.py fail_on_warning: true build: os: ubuntu-24.04 tools: # For available versions, see: # https://docs.readthedocs.io/en/stable/config-file/v2.html#build-tools-python python: '3.14' # Keep in sync with .github/workflows/checks.yml python: install: - requirements: docs/requirements.txt - path: . scrapy-w3lib-d6b4a87/CODE_OF_CONDUCT.md000066400000000000000000000126111525715767700173000ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [opensource@zyte.com](mailto:opensource@zyte.com) All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations scrapy-w3lib-d6b4a87/LICENSE000066400000000000000000000027651525715767700155170ustar00rootroot00000000000000Copyright (c) w3lib and Scrapy developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Scrapy nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. scrapy-w3lib-d6b4a87/NEWS000066400000000000000000000505231525715767700152040ustar00rootroot00000000000000w3lib release notes =================== 2.5.0 (2026-09-30) ------------------ New features: - Added support for Python 3.15 (#295). - Added :func:`~w3lib.url.add_http_if_no_scheme`, ported from Scrapy, which adds ``http`` as the default scheme to a URL that has none (#309). - ``w3lib.url.parse_qsl_to_bytes``, :func:`~w3lib.url.url_query_parameter`, :func:`~w3lib.url.add_or_replace_parameter`, :func:`~w3lib.url.add_or_replace_parameters` and :func:`~w3lib.url.canonicalize_url` now accept a *separator* (or *query_separator* for :func:`~w3lib.url.canonicalize_url`) keyword argument, to support query strings that use a separator other than ``&`` (#167). - :func:`~w3lib.html.get_base_url` and :func:`~w3lib.html.get_meta_refresh` now accept a *max_scan* keyword argument, an upper bound on how much of the document they look at (#336). - Improved the performance of most :mod:`w3lib.url` functions, :func:`~w3lib.url.safe_url_string` in particular (#257), and of some :mod:`w3lib.html` functions (#256). - :func:`~w3lib.html.get_base_url` and :func:`~w3lib.html.get_meta_refresh` are now several times faster on typical pages, which have no ```` tag and no ```` refresh tag (#331, #332, #334, #338). Deprecations and removals: - The ``w3lib.util`` module is deprecated, and now emits a :exc:`DeprecationWarning` on import (#322). - The undocumented ``w3lib_replace`` codec error handler is no longer registered (#318). Security and correctness fixes: - :func:`~w3lib.url.safe_url_string`, :func:`~w3lib.url.canonicalize_url` and ``w3lib.url.parse_url`` no longer disagree with how browsers and :mod:`urllib.parse` read a URL in the following cases, which could let a URL resolve to a different host or path than the one these functions reported: - ``\`` is now treated like ``/`` in the authority and path of special-scheme URLs (#285). - An NFKC-normalized backslash in the host is now rejected, like other normalized authority delimiters already were (#280). - ASCII tab, carriage return and line feed characters are now stripped from the whole URL, including the host (#301). Additionally, :func:`~w3lib.url.safe_url_string` now adds a ``/`` path to a URL that has a query but no path, since some HTTP clients otherwise send the query alone as the request target (#297), and no longer raises :exc:`UnicodeDecodeError` for a host that cannot be IDNA-encoded, such as one with an empty label, when *encoding* is not UTF-8 (#319). - :func:`~w3lib.url.canonicalize_url` now resolves dot segments (``.`` and ``..``) in the path and normalizes IPv6 addresses in the host, so that equivalent URLs canonicalize the same (#308), and keeps percent-encoded characters whose decoding would change their meaning, such as a semicolon (``%3B``, a path parameter delimiter, #323) or a percent sign (``%25``, which would otherwise decode to a bare ``%``, #306), in the path encoded. - :func:`~w3lib.url.canonicalize_url` no longer IDNA-encodes the userinfo of a URL together with its host, which changed both, e.g. ``http://user@éxample.com`` became ``http://xn--user@xample-fbb.com`` (#279). - :func:`~w3lib.url.safe_download_url` now resolves percent-encoded dot segments, such as ``%2e`` or ``%2e%2e``, like ``.`` and ``..`` (#320), and decides whether the path keeps its trailing ``/`` based on the path alone, rather than on whether the whole URL ends with ``/`` (#311). - :func:`~w3lib.url.url_query_parameter` now accepts a ``bytes`` URL, instead of parsing its ``b'…'`` representation (#325), and :func:`~w3lib.url.url_query_cleaner` accepts one as well, instead of raising :exc:`TypeError`, while the type hint of its *parameterlist* argument no longer claims to accept ``bytes`` items, which never matched anything (#257, #326). - :func:`~w3lib.url.path_to_file_uri` and :func:`~w3lib.url.file_uri_to_path` now round-trip Windows UNC paths, ``\\server\share\file`` becoming ``file://server/share/file`` (#324), and :func:`~w3lib.url.file_uri_to_path` no longer raises for a path that starts with an extra pair of slashes, such as ``////foo/bar`` (#327). - Fixed excessive backtracking on malformed input, which could be used for denial of service, in :func:`~w3lib.html.get_base_url` (#264), :func:`~w3lib.html.get_meta_refresh` (#266, #288), :func:`~w3lib.html.remove_tags_with_content` (#271), :func:`~w3lib.html.replace_tags` and :func:`~w3lib.html.remove_tags` (#268, #286), and :func:`~w3lib.html.unquote_markup` on unclosed CDATA sections (#289). - :func:`~w3lib.html.get_base_url` no longer picks up a ```` tag written as text inside ````, now also recognizing a closing tag followed by whitespace, ``/`` or another token (#302). - :func:`~w3lib.url.parse_data_uri` no longer raises on an empty quoted parameter value, such as ``charset=""`` (#310). - :func:`~w3lib.html.replace_entities` and :func:`~w3lib.html.get_meta_refresh` now only treat ASCII digits as numeric character references and refresh intervals, matching browsers (#292). - :func:`~w3lib.html.replace_entities` now resolves a null or surrogate numeric character reference, such as ``�`` or ``�``, to U+FFFD, as browsers do, instead of producing a NUL or a lone surrogate that cannot be encoded (#321). - :func:`~w3lib.encoding.resolve_encoding`, and with it every function that detects the encoding of a response, no longer resolves UTF-7, which browsers do not support and which lets ASCII-only bytes smuggle markup past filters (#307). - :func:`~w3lib.encoding.http_content_type_encoding` now recognizes a quoted ``charset`` parameter value, and no longer stops matching a valid ``charset`` because of what follows it or of a quoted-string parameter value that itself contains ``charset`` (#291, #293). - :func:`~w3lib.encoding.html_body_declared_encoding` now skips HTML comments, like :func:`~w3lib.html.get_base_url` and :func:`~w3lib.html.get_meta_refresh` already did (#305), and finds a charset declaration regardless of the order of the attributes in the tag, of how the ``http-equiv`` pragma is spelled, e.g. ``httpequiv="ContentType"``, and of what surrounds ``charset=`` within a ``content`` attribute value (#299, #337). - :func:`~w3lib.encoding.html_to_unicode` now decodes a lead ``0x80`` byte as the euro sign when the encoding is GB18030, matching the WHATWG Encoding Standard (#300), and decodes a BOM-less ``utf-16`` or ``utf-32`` encoding declared in the body or auto-detected as big-endian, as it already did for one declared in the ``Content-Type`` header (#317). - :func:`~w3lib.html.replace_tags`, :func:`~w3lib.html.remove_tags` and :func:`~w3lib.html.remove_tags_with_content` no longer end a tag at an angle bracket inside a quoted attribute value, such as the ``>`` of ``a>b`` (#343). - :func:`~w3lib.html.replace_entities` and :func:`~w3lib.html.unquote_markup` no longer consume *keep* when it is an iterator, such as a generator, which left some entities unkept (#342, #345), and :func:`~w3lib.html.remove_tags` no longer raises :exc:`ValueError` when *which_ones* or *keep* is an empty iterator and the other one is not (#345). - :func:`~w3lib.html.get_meta_refresh` no longer reports a redirect for a refresh ``content`` value that browsers do not follow because it uses non-ASCII whitespace, such as U+00A0 (#353). - :func:`~w3lib.html.get_meta_refresh` no longer prints the HTML content it was given to stdout when a :exc:`UnicodeDecodeError` is raised (#256). - Tests, benchmarking and CI improvements (#247, #259, #262, #281, #296, #304, #313, #314, #329, #335, #340, #344, #350). 2.4.1 (2026-03-20) ------------------ - :func:`~w3lib.url.safe_url_string` now preserves IPv6 brackets in the URL netloc (#253). 2.4.0 (2026-01-29) ------------------ - Dropped support for Python 3.9 and PyPy 3.10 (#250). - Added support for Python 3.14 and PyPy 3.11 (#241, #245). - Improved performance of :func:`~w3lib.http.headers_raw_to_dict` and :func:`~w3lib.http.headers_dict_to_raw` (#246). - Switched the build system to ``hatchling`` (#243). - The obsolete ``sphinx-hoverxref`` extension is no longer used to build the docs (#244). - Tests and CI improvements (#237, #238, #240, #242, #248, #251). 2.3.1 (2025-01-27) ------------------ - Fix a merge error, no code changes. 2.3.0 (2025-01-27) ------------------ - Dropped Python 3.8 support (#232). - Removed the following functions, deprecated in 2.0.0: - ``w3lib.util.str_to_unicode`` - ``w3lib.util.to_native_str`` - ``w3lib.util.unicode_to_str`` (#235). - Added Python 3.13 support (#232). - Fixed running tests with newer point releases of Python 3.10 and 3.11 (#233). - Cleanup and CI improvements (#232, #234). 2.2.1 (2024-06-12) ------------------ - :func:`~w3lib.url.canonicalize_url` no longer applies lowercase to the userinfo URL component. (#229, #230) 2.2.0 (2024-06-05) ------------------ - Dropped Python 3.7 support (#214). - Added Python 3.12 and PyPy 3.10 support (#218). - Added the description to the package metadata (#227). - Improved type hints (#226). - Added ``.readthedocs.yml`` (#219). - Updated the intersphinx URLs (#224). - Added the ``pre-commit`` configuration, code reformatted with ``black`` (#220). - Updated CI configuration (#217, #227). 2.1.2 (2023-08-03) ------------------ - Fix test failures on Python 3.11.4+ (#212, #213). - Fix an incorrect type hint (#211). - Add project URLs to setup.py (#215). 2.1.1 (2022-12-09) ------------------ - :func:`~w3lib.url.safe_url_string`, :func:`~w3lib.url.safe_download_url` and :func:`~w3lib.url.canonicalize_url` now strip whitespace and control characters urls according to the URL living standard. 2.1.0 (2022-11-28) ------------------ - Dropped Python 3.6 support, and made Python 3.11 support official. (#195, #200) - :func:`~w3lib.url.safe_url_string` now generates safer URLs. To make URLs safer for the `URL living standard`_: .. _URL living standard: https://url.spec.whatwg.org/ - ``;=`` are percent-encoded in the URL username. - ``;:=`` are percent-encoded in the URL password. - ``'`` is percent-encoded in the URL query if the URL scheme is `special `__. To make URLs safer for `RFC 2396`_ and `RFC 3986`_, ``|[]`` are percent-encoded in URL paths, queries, and fragments. .. _RFC 2396: https://www.ietf.org/rfc/rfc2396.txt .. _RFC 3986: https://www.ietf.org/rfc/rfc3986.txt (#80, #203) - :func:`~w3lib.encoding.html_to_unicode` now checks for the `byte order mark`_ before inspecting the ``Content-Type`` header when determining the content encoding, in line with the `URL living standard`_. (#189, #191) .. _byte order mark: https://en.wikipedia.org/wiki/Byte_order_mark - :func:`~w3lib.url.canonicalize_url` now strips spaces from the input URL, to be more in line with the `URL living standard`_. (#132, #136) - :func:`~w3lib.html.get_base_url` now ignores HTML comments. (#70, #77) - Fixed :func:`~w3lib.url.safe_url_string` re-encoding percent signs on the URL username and password even when they were being used as part of an escape sequence. (#187, #196) - Fixed :func:`~w3lib.http.basic_auth_header` using the wrong flavor of base64 encoding, which could prevent authentication in rare cases. (#181, #192) - Fixed :func:`~w3lib.html.replace_entities` raising :exc:`OverflowError` in some cases due to `a bug in CPython `__. (#199, #202) - Improved typing and fixed typing issues. (#190, #206) - Made CI and test improvements. (#197, #198) - Adopted a Code of Conduct. (#194) 2.0.1 (2022-08-11) ------------------ Minor documentation fix (release date is set in the changelog). 2.0.0 (2022-08-11) ------------------ Backwards incompatible changes: - Python 2 is no longer supported; Python 3.6+ is required now (#168, #175). - :func:`w3lib.url.safe_url_string` and :func:`w3lib.url.canonicalize_url` no longer convert "%23" to "#" when it appears in the URL path. This is a bug fix. It's listed as a backward-incomatible change because in some cases the output of :func:`w3lib.url.canonicalize_url` is going to change, and so, if this output is used to generate URL fingerprints, new fingerprints might be incompatible with those created with the previous w3lib versions (#141). Deprecation removals (#169): - The ``w3lib.form`` module is removed. - The ``w3lib.html.remove_entities`` function is removed. - The ``w3lib.url.urljoin_rfc`` function is removed. The following functions are deprecated, and will be removed in future releases (#170): - ``w3lib.util.str_to_unicode`` - ``w3lib.util.unicode_to_str`` - ``w3lib.util.to_native_str`` Other improvements and bug fixes: - Type annotations are added (#172, #184). - Added support for Python 3.9 and 3.10 (#168, #176). - Fixed :func:`w3lib.html.get_meta_refresh` for ```` tags where ``http-equiv`` is written after ``content`` (#179). - Fixed :func:`w3lib.url.safe_url_string` for IDNA domains with ports (#174). - :func:`w3lib.url.url_query_cleaner` no longer adds an unneeded ``#`` when ``keep_fragments=True`` is passed, and the URL doesn't have a fragment (#159). - Removed a workaround for an ancient pathname2url bug (#142) - CI is migrated to GitHub Actions (#166, #177); other CI improvements (#160, #182). - The code is formatted using black (#173). 1.22.0 (2020-05-13) ------------------- - Python 3.4 is no longer supported (issue #156) - :func:`w3lib.url.safe_url_string` now supports an optional ``quote_path`` parameter to disable the percent-encoding of the URL path (issue #119) - :func:`w3lib.url.add_or_replace_parameter` and :func:`w3lib.url.add_or_replace_parameters` no longer remove duplicate parameters from the original query string that are not being added or replaced (issue #126) - :func:`w3lib.html.remove_tags` now raises a :exc:`ValueError` exception instead of :exc:`AssertionError` when using both the ``which_ones`` and the ``keep`` parameters (issue #154) - Test improvements (issues #143, #146, #148, #149) - Documentation improvements (issues #140, #144, #145, #151, #152, #153) - Code cleanup (issue #139) 1.21.0 (2019-08-09) ------------------- - Add the ``encoding`` and ``path_encoding`` parameters to :func:`w3lib.url.safe_download_url` (issue #118) - :func:`w3lib.url.safe_url_string` now also removes tabs and new lines (issue #133) - :func:`w3lib.html.remove_comments` now also removes truncated comments (issue #129) - :func:`w3lib.html.remove_tags_with_content` no longer removes tags which start with the same text as one of the specified tags (issue #114) - Recommend pytest instead of nose to run tests (issue #124) 1.20.0 (2019-01-11) ------------------- - Fix url_query_cleaner to do not append "?" to urls without a query string (issue #109) - Add support for Python 3.7 and drop Python 3.3 (issue #113) - Add `w3lib.url.add_or_replace_parameters` helper (issue #117) - Documentation fixes (issue #115) 1.19.0 (2018-01-25) ------------------- - Add a workaround for CPython segfault (https://bugs.python.org/issue32583) which affect w3lib.encoding functions. This is technically **backwards incompatible** because it changes the way non-decodable bytes are replaced (in some cases instead of two ``\ufffd`` chars you can get one). As a side effect, the fix speeds up decoding in Python 3.4+. - Add 'encoding' parameter for w3lib.http.basic_auth_header. - Fix pypy testing setup, add pypy3 to CI. 1.18.0 (2017-08-03) ------------------- - Include additional assets used for distribution packages in the source tarball - Consider ``[`` and ``]`` as safe characters in path and query components of URLs, i.e. they are not escaped anymore - Disable codecov project coverage check 1.17.0 (2017-02-08) ------------------- - Add Python 3.5 and 3.6 support - Add ``w3lib.url.parse_data_uri`` helper for parsing "data:" URIs - Add ``w3lib.html.strip_html5_whitespace`` function to strip leading and trailing whitespace as per W3C recommendations, e.g. for cleaning "href" attribute values - Fix ``w3lib.http.headers_raw_to_dict`` for multiple headers with same name - Do not distribute tests/test_*.pyc artifacts 1.16.0 (2016-11-10) ------------------- - ``canonicalize_url()`` and ``safe_url_string()``: strip ":" when no port is specified (as per `RFC 3986`_; see also https://github.com/scrapy/scrapy/issues/2377) - ``url_query_cleaner()``: support new ``keep_fragments`` argument (defaulting to ``False``) 1.15.0 (2016-07-29) ------------------- - Add ``canonicalize_url()`` to ``w3lib.url`` 1.14.3 (2016-07-14) ------------------- Bugfix release: - Handle IDNA encoding failures in ``safe_url_string()`` (issue #62) 1.14.2 (2016-04-11) ------------------- Bugfix release: - fix function import for (deprecated) ``urljoin_rfc`` (issue #51) - only expose wanted functions from ``w3lib.url``, via ``__all__`` (see issue #54, https://github.com/scrapy/scrapy/issues/1917) 1.14.1 (2016-04-07) ------------------- Bugfix release: - For bytes URLs, when supplied encoding (or default UTF8) is wrong, ``safe_url_string`` falls back to percent-encoding offending bytes. 1.14.0 (2016-04-06) ------------------- Changes to safe_url_string: - proper handling of non-ASCII characters in Python2 and Python3 - support IDNs - new `path_encoding` to override default UTF-8 when serializing non-ASCII characters before percent-encoding html_body_declared_encoding also detects encoding when not sole attribute in ````. Package is now properly marked as ``zip_safe``. 1.13.0 (2015-11-05) ------------------- - remove_tags removes uppercase tags as well; - ignore meta-redirects inside script or noscript tags by default, but add an option to not ignore them; - replace_entities now handles entities without trailing semicolon; - fixed uncaught UnicodeDecodeError when decoding entities. 1.12.0 (2015-06-29) ------------------- - meta_refresh regex now handles leading newlines and whitespaces in the url; - include tests folder in source distribution. 1.11.0 (2015-01-13) ------------------- - url_query_cleaner now supports str or list parameters; - add support for resolving base URLs in tags with attributes before href. 1.10.0 (2014-08-20) ------------------- - reverted all 1.9.0 changes. 1.9.0 (2014-08-16) ------------------ - all url-related functions accept bytes and unicode and now return bytes. 1.8.1 (2014-08-14) ------------------ - w3lib.http.basic_auth_header now returns bytes 1.8.0 (2014-07-31) ------------------ - add support for big5-hkscs encoding. 1.7.1 (2014-07-26) ------------------ - PY3 fixed headers_raw_to_dict and headers_dict_to_raw; - documentation improvements; - provide wheels. 1.6 (2014-06-03) ---------------- - w3lib.form.encode_multipart is deprecated; - docstrings and docs are improved; - w3lib.url.add_or_replace_parameter is re-implemented on top of stdlib functions; - remove_entities is renamed to replace_entities. 1.5 (2013-11-09) ---------------- - Python 2.6 support is dropped. 1.4 (2013-10-18) ---------------- - Python 3 support; - get_meta_refresh encoding handling is fixed; - check for '?' in add_or_replace_parameter; - ISO-8859-1 is used for HTTP Basic Auth; - fixed unicode handling in replace_escape_chars; 1.3 (2012-05-13) ---------------- - support non-standard gb_2312_80 encoding; - drop Python 2.5 support. 1.2 (2012-05-02) ---------------- - Detect encoding for content attr before http-equiv in meta tag. 1.1 (2012-04-18) ---------------- - w3lib.html.remove_comments handles multiline comments; - Added w3lib.encoding module, containing functions for working with character encoding, like encoding autodetection from HTML pages. - w3lib.url.urljoin_rfc is deprecated. 1.0 (2011-04-17) ---------------- First release of w3lib. scrapy-w3lib-d6b4a87/README.rst000066400000000000000000000016471525715767700161770ustar00rootroot00000000000000===== w3lib ===== .. image:: https://github.com/scrapy/w3lib/actions/workflows/test.yml/badge.svg :target: https://github.com/scrapy/w3lib/actions/workflows/test.yml .. image:: https://img.shields.io/codecov/c/github/scrapy/w3lib/master.svg :target: https://codecov.io/github/scrapy/w3lib?branch=master :alt: Coverage report Overview ======== This is a Python library of web-related functions, such as: * remove comments, or tags from HTML snippets * extract base url from HTML snippets * translate entities on HTML strings * convert raw HTTP headers to dicts and vice-versa * construct HTTP auth header * converting HTML pages to unicode * sanitize urls (like browsers do) * extract arguments from urls Requirements ============ Python 3.10+ Install ======= ``pip install w3lib`` Documentation ============= See https://w3lib.readthedocs.io/ License ======= The w3lib library is licensed under the BSD license. scrapy-w3lib-d6b4a87/codecov.yml000066400000000000000000000002331525715767700166430ustar00rootroot00000000000000--- comment: layout: header, diff, tree coverage: status: patch: false project: default: target: 100% scrapy-w3lib-d6b4a87/conftest.py000066400000000000000000000001021525715767700166700ustar00rootroot00000000000000collect_ignore = [ # warning on import "w3lib/util.py", ] scrapy-w3lib-d6b4a87/docs/000077500000000000000000000000001525715767700154305ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/docs/Makefile000066400000000000000000000126701525715767700170760ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/w3lib.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/w3lib.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/w3lib" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/w3lib" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." scrapy-w3lib-d6b4a87/docs/conf.py000066400000000000000000000203761525715767700167370ustar00rootroot00000000000000# w3lib documentation build configuration file, created by # sphinx-quickstart on Sun Jan 26 22:19:38 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys from pathlib import Path # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, str(Path(__file__).parent.parent)) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "notfound.extension", "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = {".rst": "restructuredtext"} # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "w3lib" project_copyright = "2014, w3lib developers" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = "2.5.0" # The short X.Y version. version = ".".join(release.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "w3libdoc" # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "w3lib.tex", "w3lib Documentation", "w3lib developers", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "w3lib", "w3lib Documentation", ["w3lib developers"], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "w3lib", "w3lib Documentation", "w3lib developers", "w3lib", "One line description of project.", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "pytest": ("https://docs.pytest.org/en/latest", None), "python": ("https://docs.python.org/3", None), "scrapy": ("https://docs.scrapy.org/en/latest", None), "tox": ("https://tox.wiki/en/latest", None), } # -- Nitpicking options ------------------------------------------------------- nitpicky = True scrapy-w3lib-d6b4a87/docs/index.rst000066400000000000000000000026711525715767700172770ustar00rootroot00000000000000Welcome to w3lib's documentation! ================================= Overview ======== This is a Python library of web-related functions, such as: * remove comments, or tags from HTML snippets * extract base url from HTML snippets * translate entities on HTML strings * convert raw HTTP headers to dicts and vice-versa * construct HTTP auth header * converting HTML pages to unicode * sanitize urls (like browsers do) * extract arguments from urls The w3lib library is licensed under the BSD license. Modules ======= .. toctree:: :maxdepth: 4 w3lib Requirements ============ Python 3.10+ Install ======= ``pip install w3lib`` Tests ===== :doc:`pytest ` is the preferred way to run tests. Just run: ``pytest`` from the root directory to execute tests using the default Python interpreter. :doc:`tox ` could be used to run tests for all supported Python versions. Install it (using 'pip install tox') and then run ``tox`` from the root directory - tests will be executed for all available Python interpreters. Changelog ========= .. include:: ../NEWS :start-line: 3 History ------- The code of w3lib was originally part of the :doc:`Scrapy framework ` but was later stripped out of Scrapy, with the aim of make it more reusable and to provide a useful library of web functions without depending on Scrapy. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` scrapy-w3lib-d6b4a87/docs/make.bat000066400000000000000000000117461525715767700170460ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\w3lib.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\w3lib.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end scrapy-w3lib-d6b4a87/docs/requirements.txt000066400000000000000000000000551525715767700207140ustar00rootroot00000000000000sphinx sphinx-notfound-page sphinx_rtd_theme scrapy-w3lib-d6b4a87/docs/w3lib.rst000066400000000000000000000007331525715767700172050ustar00rootroot00000000000000w3lib Package ============= :mod:`~w3lib.encoding` Module ----------------------------- .. automodule:: w3lib.encoding :members: :mod:`~w3lib.html` Module ------------------------- .. automodule:: w3lib.html :members: :mod:`~w3lib.http` Module ------------------------- .. automodule:: w3lib.http :members: :mod:`~w3lib.url` Module ------------------------ .. automodule:: w3lib.url :members: .. autoclass:: ParseDataURIResult :members: scrapy-w3lib-d6b4a87/pyproject.toml000066400000000000000000000133001525715767700174110ustar00rootroot00000000000000[build-system] requires = ["hatchling>=1.27.0"] build-backend = "hatchling.build" [project] name = "w3lib" description = "Library of web-related functions" readme = "README.rst" license = "BSD-3-Clause" license-files = ["LICENSE"] authors = [ { name = "Scrapy project", email = "info@scrapy.org" }, ] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ] requires-python = ">=3.10" dynamic = ["version"] [project.urls] Homepage = "https://github.com/scrapy/w3lib" Documentation = "https://w3lib.readthedocs.io/en/latest/" Source = "https://github.com/scrapy/w3lib" Tracker = "https://github.com/scrapy/w3lib/issues" "Release notes" = "https://w3lib.readthedocs.io/en/latest/#changelog" [tool.hatch.version] path = "w3lib/__init__.py" [tool.hatch.build.targets.sdist] include = [ "/docs", "/w3lib", "/tests", "/NEWS", "/codecov.yml", "/tox.ini", ] [tool.bumpversion] current_version = "2.5.0" commit = true tag = true tag_name = "v{new_version}" [[tool.bumpversion.files]] filename = "w3lib/__init__.py" [[tool.bumpversion.files]] filename = "docs/conf.py" [[tool.bumpversion.files]] filename = "NEWS" search = "\\(unreleased\\)$" replace = "({now:%Y-%m-%d})" regex = true [tool.coverage.run] branch = true [tool.mypy] strict = true [[tool.mypy.overrides]] # Allow test functions to be untyped module = "tests.*" allow_untyped_defs = true [tool.pylint.MASTER] persistent = "no" [tool.pylint."MESSAGES CONTROL"] enable = [ "useless-suppression", ] disable = [ "fixme", "import-error", "import-outside-toplevel", "invalid-name", "line-too-long", "missing-class-docstring", "missing-function-docstring", "missing-module-docstring", "raise-missing-from", "redefined-builtin", "redefined-outer-name", "too-few-public-methods", "too-many-arguments", "too-many-branches", "too-many-lines", "too-many-positional-arguments", "too-many-public-methods", "unused-argument", "unused-import", "unused-variable", "useless-import-alias", "possibly-used-before-assignment", ] [tool.ruff.lint] extend-select = [ # flake8-builtins "A", # flake8-async "ASYNC", # flake8-bugbear "B", # flake8-comprehensions "C4", # flake8-commas "COM", # pydocstyle "D", # flake8-future-annotations "FA", # flynt "FLY", # refurb "FURB", # isort "I", # flake8-implicit-str-concat "ISC", # flake8-logging "LOG", # Perflint "PERF", # pygrep-hooks "PGH", # flake8-pie "PIE", # pylint "PL", # flake8-pytest-style "PT", # flake8-use-pathlib "PTH", # flake8-pyi "PYI", # flake8-quotes "Q", # flake8-return "RET", # flake8-raise "RSE", # Ruff-specific rules "RUF", # flake8-bandit "S", # flake8-simplify "SIM", # flake8-slots "SLOT", # flake8-debugger "T10", # flake8-type-checking "TC", # pyupgrade "UP", # pycodestyle warnings "W", # flake8-2020 "YTT", ] ignore = [ # Within an `except` clause, raise exceptions with `raise ... from` "B904", # Trailing comma missing "COM812", # Missing docstring in public module "D100", # Missing docstring in public class "D101", # Missing docstring in public method "D102", # Missing docstring in public function "D103", # Missing docstring in public package "D104", # Missing docstring in magic method "D105", # Missing docstring in public nested class "D106", # Missing docstring in __init__ "D107", # One-line docstring should fit on one line with quotes "D200", # No blank lines allowed after function docstring "D202", # 1 blank line required between summary line and description "D205", # Multi-line docstring closing quotes should be on a separate line "D209", # First line should end with a period "D400", # First line should be in imperative mood; try rephrasing "D401", # First line should not be the function's "signature" "D402", # First word of the first line should be properly capitalized "D403", # No blank lines allowed between a section header and its content "D412", # Too many return statements "PLR0911", # Too many branches "PLR0912", # Too many arguments in function definition "PLR0913", # Too many statements "PLR0915", # Magic value used in comparison "PLR2004", # String contains ambiguous {}. "RUF001", # Docstring contains ambiguous {}. "RUF002", # Comment contains ambiguous {}. "RUF003", # Mutable class attributes should be annotated with `typing.ClassVar` "RUF012", # Use of `assert` detected "S101", # Import alias does not rename original package "PLC0414", # Too many positional arguments "PLR0917", # Private name import "PLC2701", ] [tool.ruff.lint.isort] split-on-trailing-comma = false combine-as-imports = true [tool.ruff.lint.pydocstyle] convention = "pep257" scrapy-w3lib-d6b4a87/tests/000077500000000000000000000000001525715767700156425ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/tests/__init__.py000066400000000000000000000000001525715767700177410ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/tests/benchmarks/000077500000000000000000000000001525715767700177575ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/tests/benchmarks/__init__.py000066400000000000000000000006211525715767700220670ustar00rootroot00000000000000import sys from collections.abc import Callable, Iterable from typing import Any, TypeAlias import pytest pytest.importorskip("pytest_codspeed", reason="Benchmark tests require pytest-codspeed") BENCHMARK_MARKS = [ pytest.mark.benchmark, pytest.mark.skipif("PyPy" in sys.version, reason="CodSpeed doesn't support PyPy"), ] CasesMapType: TypeAlias = dict[Callable[..., Any], Iterable[Any]] scrapy-w3lib-d6b4a87/tests/benchmarks/pages/000077500000000000000000000000001525715767700210565ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/tests/benchmarks/pages/base-href-in-head.html000066400000000000000000000342101525715767700251030ustar00rootroot00000000000000
scrapy-w3lib-d6b4a87/tests/benchmarks/pages/base-without-href.html000066400000000000000000061735601525715767700253230ustar00rootroot00000000000000 Distinctio quo Amet in Dolores-Deleniti Veniam, UT - 796 Eveniet in Dolores-Deleniti Veniam, UT | Itaque

Quo fuga

Minim

Aute/ipsum

Quis fuga

Distinctio quo Amet in Dolores-Deleniti Veniam, UT

793 eveniet
CUM 19 CUM QUILOWERED FEES
Maxime: $930
1 at: $1,008 • 2 at: $1,175
16 ipsum similique • Fuga laboris • Facilis
Odio do Dolores
 | 108 Cupidatat Id, Dolores, UT 30909
(555) 018-8957
CUM 33 CUM QUI
$1,399+/mo
2 aute2 ipsum1,170 id ad
15 ipsum similique • Fuga laboris • L/C
Mollit Saepe Perferendis Nam
 | 255 Perferendis Nam, Dolores, UT 30909
(555) 017-7297
$500 EOS
1 at: $950
2 at: $1,225
14 ipsum similique • Fuga laboris • Facilis
Dolorum do Dolores
 | 2900 Similique Sint, Dolores, UT 30909
(555) 013-2910
1 VELIT FUGA
2 at: $1,215
3 at: $1,404
24 ipsum similique • Fuga laboris • Facilis
Sed Labore
 | 1020 Anim Nam, Dolores, UT 30909
(555) 012-4136
CUM 9 CUM QUI3D WALKTHROUGH
1 at: $999
2 at: $1,139
18 ipsum similique • Fuga laboris • L/C
Excepteur
 | 1811 Facere Ex, Dolores, UT 30909
(555) 010-2410
QUAS
1 at: $912
2 at: $1,044 • 3 at: $1,357
12 ipsum similique • Fuga laboris • Quo-excepteur
Repellat Distinctio
 | 1355 Laborum Ex, Dolores, UT 30909
(555) 017-4856
Occaecat at Nisi Est Cum Vero - 926 Debitis Nihil Ex, Dolores, UT, 30907, 1-2 hic, 1-2 sunt, [veniam Veniam]
Nisi Est Cum Vero - 926 Debitis Nihil Ex, Dolores, UT, 30907
$998+/mo
1-2 hic1-2 sunt525-1,000 id ad
Nisi Est Cum Vero
 | 926 Debitis Nihil Ex, Dolores, UT 30907
Occaecat at Libero Dolores - 3232 Mollitia Eos, Dolores, UT, 30909, 1-2 hic, 1-2 sunt, [veniam Veniam]
Libero Dolores - 3232 Mollitia Eos, Dolores, UT, 30909
$860+/mo
1-2 hic1-2 sunt680-860 id ad
Libero Dolores
 | 3232 Mollitia Eos, Dolores, UT 30909
Occaecat at Pariatur at Voluptas Minim Distinctio - 1075 Placeat Ex, Dolores, UT, 30909, 1-3 hic, 1-2 sunt, [veniam Veniam]
Pariatur at Voluptas Minim Distinctio - 1075 Placeat Ex, Dolores, UT, 30909
$1,079+/mo
1-3 hic1-2 sunt782-1,318 id ad
Pariatur at Voluptas Minim Distinctio
 | 1075 Placeat Ex, Dolores, UT 30909
Occaecat at Nostrud - 249 Hic Iusto Ex, Dolores, UT, 30909, 1-2 hic, 1 sunt, [veniam Veniam]
Nostrud - 249 Hic Iusto Ex, Dolores, UT, 30909
$999+/mo
1-2 hic1 sunt609-886 id ad
Nostrud
 | 249 Hic Iusto Ex, Dolores, UT 30909
Occaecat at Debitis Nihil Nostrud - 100 Est Est Id, Dolores, UT, 30907, 1-2 hic, 1-2 sunt, [veniam Veniam]
Debitis Nihil Nostrud - 100 Est Est Id, Dolores, UT, 30907
$915+/mo
1-2 hic1-2 sunt626-1,004 id ad
Debitis Nihil Nostrud
 | 100 Est Est Id, Dolores, UT 30907
Occaecat at Sed Nobis - 9000 Provident Eos, Dolores, UT, 30909, 1-3 hic, 1-2 sunt, [veniam Veniam]
Sed Nobis - 9000 Provident Eos, Dolores, UT, 30909
$1,500+/mo
1-3 hic1-2 sunt850-1,441 id ad
Sed Nobis
 | 9000 Provident Eos, Dolores, UT 30909
Occaecat at Mollit Saepe Dolores - 1400 Mollit Saepe Id, Dolores, UT, 30909, 2 aute, 2 ipsum, [veniam Veniam]
Mollit Saepe Dolores - 1400 Mollit Saepe Id, Dolores, UT, 30909
$1,459+/mo
2 aute2 ipsum1,170 id ad
Mollit Saepe Dolores
 | 1400 Mollit Saepe Id, Dolores, UT 30909
Occaecat at Cillum Minim Debitis Elit - 934 Accusamus Id, Dolores, UT, 30909, 0-2 aute, 1-1.5 sunt, [veniam Veniam]
Cillum Minim Debitis Elit - 934 Accusamus Id, Dolores, UT, 30909
$1,120+/mo
Maxime-2 hic1-1.5 sunt520-1,008 id ad
Cillum Minim Debitis Elit
 | 934 Accusamus Id, Dolores, UT 30909
Occaecat at Eligendi Minim - 1100 Laboris ID, Consequat, UT, 30813, 1-2 hic, 1-2 sunt, [veniam Veniam]
Eligendi Minim - 1100 Laboris ID, Consequat, UT, 30813
$1,250+/mo
1-2 hic1-2 sunt725-984 id ad
Eligendi Minim
 | 1100 Laboris ID, Consequat, UT 30813
Occaecat at Molestias Maxime Quibusdam - 1903 Maxime Ex, Dolores, UT, 30909, 3 aute, 3 ipsum, [veniam Veniam]
Molestias Maxime Quibusdam - 1903 Maxime Ex, Dolores, UT, 30909
$1,775/mo
3 aute3 ipsum1,477-1,600 id ad
Molestias Maxime Quibusdam
 | 1903 Maxime Ex, Dolores, UT 30909
Occaecat at Occaecat Distinctio - 2905 Voluptate Id, Dolores, UT, 30909, 2 aute, 2 ipsum, [veniam Veniam]
Occaecat Distinctio - 2905 Voluptate Id, Dolores, UT, 30909
$1,020/mo
2 aute2 ipsum1,051 id ad
Occaecat Distinctio
 | 2905 Voluptate Id, Dolores, UT 30909
Occaecat at Nobis at sed Optio - 3122 Sapiente Ex, Dolores, UT, 30909, 1-2 hic, 1-2 sunt, [veniam Veniam]
Nobis at sed Optio - 3122 Sapiente Ex, Dolores, UT, 30909
$914+/mo
1-2 hic1-2 sunt580-916 id ad
Nobis at sed Optio
 | 3122 Sapiente Ex, Dolores, UT 30909
Occaecat at Cupidatat - 1840 Reprehenderit Ex, Dolores, UT, 30904, 1 hic, 1 sunt, [veniam Veniam]
Cupidatat - 1840 Reprehenderit Ex, Dolores, UT, 30904
$910/mo
1 hic1 sunt567 id ad
Cupidatat
 | 1840 Reprehenderit Ex, Dolores, UT 30904
Occaecat at Laboris Quibusdam - 220 Hic Iusto Ex, Dolores, UT, 30909, 2 aute, 1.5 ipsum, [veniam Veniam]
Laboris Quibusdam - 220 Hic Iusto Ex, Dolores, UT, 30909
$1,195/mo
2 aute1.5 ipsum1,054 id ad
Laboris Quibusdam
 | 220 Hic Iusto Ex, Dolores, UT 30909
Occaecat at Commodo Earum Distinctio - 4011 Commodo Earum Ex, Dolores, UT, 30909, 2 aute, 1 sunt, [veniam Veniam]
Commodo Earum Distinctio - 4011 Commodo Earum Ex, Dolores, UT, 30909
$1,040/mo
2 aute1 sunt982 id ad
Commodo Earum Distinctio
 | 4011 Commodo Earum Ex, Dolores, UT 30909
Occaecat at Consectetur Dolore Distinctio - Molestias Excepteur Tempore Dolores - 2476 DeSerunt Ut, Dolores, UT, 30904, 1-2 hic, 1-1.5 sunt, [veniam Veniam]
Consectetur Dolore Distinctio - Molestias Excepteur Tempore Dolores - 2476 DeSerunt Ut, Dolores, UT, 30904
$1,750+/mo
1-2 hic1-1.5 sunt600-1,100 id ad
Consectetur Dolore Distinctio - Molestias Excepteur Tempore Dolores
 | 2476 DeSerunt Ut, Dolores, UT 30904
Occaecat at Sed Officiis at Veniam - 1247 Dolores Vero Sint, Dolores, UT, 30909, 3 aute, 2 ipsum, [veniam Veniam]
Sed Officiis at Veniam - 1247 Dolores Vero Sint, Dolores, UT, 30909
$2,225/mo
3 aute2 ipsum1,400 id ad
Sed Officiis at Veniam
 | 1247 Dolores Vero Sint, Dolores, UT 30909
Occaecat at Molestias Distinctio & Cumque - 1414 Possimus Id, Dolores, UT, 30906, 2-3 aute, 2 ipsum, [veniam Veniam]
Molestias Distinctio & Cumque - 1414 Possimus Id, Dolores, UT, 30906
$1,625+/mo
2-3 aute2 ipsum1,088-1,265 id ad
Molestias Distinctio & Cumque
 | 1414 Possimus Id, Dolores, UT 30906
Occaecat at Vero at Debitis Dolor Assumenda Harum - 1150 Reiciendis Sint, Dolores, UT, 30909, 1-3 hic, 1-2 sunt, [veniam Veniam]
Vero at Debitis Dolor Assumenda Harum - 1150 Reiciendis Sint, Dolores, UT, 30909
$1,135+/mo
1-3 hic1-2 sunt690-1,384 id ad
Vero at Debitis Dolor Assumenda Harum
 | 1150 Reiciendis Sint, Dolores, UT 30909
Occaecat at Cupiditate at Dolores Assumenda Harum - 3722 Libero Nam Nam, Dolores, UT, 30907, 1-3 hic, 1-2 sunt, [veniam Veniam]
Cupiditate at Dolores Assumenda Harum - 3722 Libero Nam Nam, Dolores, UT, 30907
$955+/mo
1-3 hic1-2 sunt809-1,236 id ad
Cupiditate at Dolores Assumenda Harum
 | 3722 Libero Nam Nam, Dolores, UT 30907
Occaecat at Nihil Nihil Distinctio - 950 Debitis Nihil Ex, Dolores, UT, 30907, 2 aute, 2 ipsum, [veniam Veniam]
Nihil Nihil Distinctio - 950 Debitis Nihil Ex, Dolores, UT, 30907
$1,183+/mo
2 aute2 ipsum1,100 id ad
Nihil Nihil Distinctio
 | 950 Debitis Nihil Ex, Dolores, UT 30907
Occaecat at Laboris Nihil Distinctio - 1924 B Non Ex, Dolores, UT, 30909, 1-2 hic, 1 sunt, [veniam Veniam]
Laboris Nihil Distinctio - 1924 B Non Ex, Dolores, UT, 30909
$960+/mo
1-2 hic1 sunt894-984 id ad
Laboris Nihil Distinctio
 | 1924 B Non Ex, Dolores, UT 30909
Occaecat at Impedit at 2663 - 2663 Fugiat Ex, Dolores, UT, 30906, 1-3 hic, 1-2.5 sunt, [veniam Veniam]
Impedit at 2663 - 2663 Fugiat Ex, Dolores, UT, 30906
$996+/mo
1-3 hic1-2.5 sunt793-1,450 id ad
Impedit at 2663
 | 2663 Fugiat Ex, Dolores, UT 30906
Occaecat at Sed Eos - 1812 Dolore Ut, Dolores, UT, 30904, 1-3 hic, 1-2 sunt, [veniam Veniam]
Sed Eos - 1812 Dolore Ut, Dolores, UT, 30904
$1,500+/mo
1-3 hic1-2 sunt1,238-1,832 id ad
Sed Eos
 | 1812 Dolore Ut, Dolores, UT 30904
Occaecat at Laborum Occaecat - 601 Corrupti Ad, Dolores, UT, 30907, 1-3 hic, 1-2 sunt, [veniam Veniam]
Laborum Occaecat - 601 Corrupti Ad, Dolores, UT, 30907
$1,358+/mo
1-3 hic1-2 sunt642-1,296 id ad
Laborum Occaecat
 | 601 Corrupti Ad, Dolores, UT 30907
Occaecat at Sed Amet - 1035 Consequat Id, Dolores, UT, 30909, 1-3 hic, 1-2 sunt, [veniam Veniam]
Sed Amet - 1035 Consequat Id, Dolores, UT, 30909
$1,155+/mo
1-3 hic1-2 sunt824-1,403 id ad
Sed Amet
 | 1035 Consequat Id, Dolores, UT 30909
Occaecat at Tempore at Blanditiis Distinctio - 420 Debitis Nam, Dolores, UT, 30909, 1-3 hic, 1-2 sunt, [veniam Veniam]
Tempore at Blanditiis Distinctio - 420 Debitis Nam, Dolores, UT, 30909
$1,478+/mo
1-3 hic1-2 sunt702-1,409 id ad
Tempore at Blanditiis Distinctio
 | 420 Debitis Nam, Dolores, UT 30909
Occaecat at Occaecati Distinctio - 2512 Ipsum Est, Dolores, UT, 30909, 2 aute, 2 ipsum, [veniam Veniam]
Occaecati Distinctio - 2512 Ipsum Est, Dolores, UT, 30909
$1,320/mo
2 aute2 ipsum991 id ad
Occaecati Distinctio
 | 2512 Ipsum Est, Dolores, UT 30909
Occaecat at Mollitia at Veniam - 4210 Deserunt Ex, Dolores, UT, 30906, 4 aute, 2.5 ipsum, [veniam Veniam]
Mollitia at Veniam - 4210 Deserunt Ex, Dolores, UT, 30906
$1,795+/mo
4 aute2.5 ipsum1,900 id ad
Mollitia at Veniam
 | 4210 Deserunt Ex, Dolores, UT 30906
Occaecat at Sunt Nihil - 1315 Magna Tempor Ex, Dolores, UT, 30909, 2 aute, 2 ipsum, [veniam Veniam]
Sunt Nihil - 1315 Magna Tempor Ex, Dolores, UT, 30909
$1,287+/mo
2 aute2 ipsum987-1,076 id ad
Sunt Nihil
 | 1315 Magna Tempor Ex, Dolores, UT 30909
Occaecat at Irure Facilis Anim - 3630 Irure Facilis Ex, Dolores, UT, 30906, 2 aute, 2 ipsum, [veniam Veniam]
Irure Facilis Anim - 3630 Irure Facilis Ex, Dolores, UT, 30906
$1,064/mo
2 aute2 ipsum— id ad
Irure Facilis Anim
 | 3630 Irure Facilis Ex, Dolores, UT 30906
Occaecat at Laborum Tenetur - 1311 Magna Tempor Ex, Dolores, UT, 30909, 0 aute, 1 sunt, [veniam Veniam]
Laborum Tenetur - 1311 Magna Tempor Ex, Dolores, UT, 30909
$808/mo
Maxime1 sunt400 id ad
Laborum Tenetur
 | 1311 Magna Tempor Ex, Dolores, UT 30909
Occaecat at Sed Mollit at Dolores - 2205 Doloribus Id, Dolores, UT, 30906, 2 aute, 1-1.5 sunt, [veniam Veniam]
Sed Mollit at Dolores - 2205 Doloribus Id, Dolores, UT, 30906
$1,045+/mo
2 aute1-1.5 sunt850-1,000 id ad
Sed Mollit at Dolores
 | 2205 Doloribus Id, Dolores, UT 30906
Occaecat at Dolores Commodo Distinctio 55+ - 1730 Facere Ex, Dolores, UT, 30909, 1-2 hic, 1 sunt, [veniam Veniam]
Dolores Commodo Distinctio 55+ - 1730 Facere Ex, Dolores, UT, 30909
$936+/mo
1-2 hic1 sunt660-840 id ad
Dolores Commodo Distinctio 55+
 | 1730 Facere Ex, Dolores, UT 30909
Occaecat at Sed Ducimus at Similique - 50 Earum Eveniet Id, Dolores, UT, 30909, 2-3 aute, 2 ipsum, [veniam Veniam]
Sed Ducimus at Similique - 50 Earum Eveniet Id, Dolores, UT, 30909
$1,360+/mo
2-3 aute2 ipsum1,060-1,366 id ad
Sed Ducimus at Similique
 | 50 Earum Eveniet Id, Dolores, UT 30909
Tempore quos 1 do 4 
Sed esse officiis ad nisi labore quo fuga at odio non sint omnis in fuga sunt sed Mollit Consectetur Laboris do Nostrud NAM. Nisi labore expedita esse do similique animi culpa quas Itaque sit tempor quod sed Mollit Consectetur quod sit corrupti dignissimos dolor sunt sapiente sed quod do sed ullamco laborum. Dignissimos tempor deleniti nam sed cupiditate. Similique 2026 Nostrud NAM. Cum maxime corrupti.

Sed esse officiis ad nisi labore at odio non sint omnis in fuga sunt sed Officiis Esse Eligendi laboris do Esse NAM QUI, sit ex ullamco et do Qui Hic 15 2026. Cum dignissimos ex tempor deleniti nam sed cupiditate sit fugiat at reprehenderit proident. Cum reiciendis sit ullamco ad alias fuga, cillum, do voluptatum. Eveniet ullamco mollit(s) sit Itaque irure at praesentium quo qui reprehenderit maxime, necessitatibus, do quibusdam, sit irure at esse nostrud possimus sunt qui laborum maiores sunt expedita aute culpa esse. © 2026 Esse NAM QUI

Possimus sed Itaque Nam at sed Saepe Nam Culpa
Possimus sed Itaque Nam sunt sed Quidem Odio Culpa

Sint ex

Enim harum maxime

Possimus sed Itaque Nam at sed Saepe Nam Culpa
Possimus sed Itaque Nam sunt sed Quidem Odio Culpa

Enim ex

Subsidiaries

Affiliated Business

Countries

EX flagFugiat Soluta

Canadian flagCillum

scrapy-w3lib-d6b4a87/tests/benchmarks/pages/no-base.html000066400000000000000000016723631525715767700233120ustar00rootroot00000000000000Mollitia eos facere d'quidem assumenda - Earum (75002) - Qui assumenda
Asperiores
Mollitia eos facere d'quidem assumenda

Mollitia eos facere d'quidem assumenda

Maxime cumque impedit 2013
Mollitia eos facere d'quidem assumenda

Et est quos quas

Aute in 2006, assumenda est nam incididunt d’delectus qui similique l’harum v ad voluptatibus ad eveniet duis, recusandae ad voluptas dolore et fuga do ullamco at velit ut maiores ad quas. assumenda l in s’dolorum in deleniti eos…

Accusamus ad l’recusandae

PraesentiumLibero d’recusandae (NAM)ReprehenderitSEDFacere Voluptatum

Dolorum

Earum

75002

Earum

Maxime ad l’recusandae

L’cumque

41 expedita in nobis

Dolorum nam exercitation

Optio Similique Consectetur & Veniam 6 quod B) (M/F/M)

Optio Similique Consectetur & Veniam 6 quod B) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : aujourd’hui v 04:24.

Cupiditate·z Facilis QuiS (Cillum Repellat Reprehenderit) - Aliqua Est - (B/F/M) (M/F/M)

Cupiditate·z Facilis QuiS (Cillum Repellat Reprehenderit) - Aliqua Est - (B/F/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75002 2z Necessitatibus.

Aute ad omnis : hier v 11:23.

Dolore Impedit Tenetur - Omnis d'expedita (F/B/M) (M/F/M)

Dolore Impedit Tenetur - Omnis d'expedita (F/B/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 07/09/2026.

EX Officiis (F/B/M) (M/F/M)

EX Officiis (F/B/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 02/09/2026.

Dolore Earum-Non Officiis Nobis (F/B/M) (M/F/M)

Dolore Earum-Non Officiis Nobis (F/B/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Labore 44000 Sapiente-Earum-Occaecat.

Aute ad omnis : 29/08/2026.

Labore.z ad Autem Similique Possimus - OPTIO - (B/F/M) (M/F/M)

Labore.z ad Autem Similique Possimus - OPTIO - (B/F/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 27/08/2026.

Dolore esse tempore (M/F/M)

Dolore esse tempore (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 26/08/2026.

Impedit Tenetur (F/B/M) (M/F/M)

Impedit Tenetur (F/B/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 26/08/2026.

Labore Ullamco - Nisi Labore (B/F/M) (M/F/M)

Labore Ullamco - Nisi Labore (B/F/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 24/08/2026.

Non Tempore Tenetur Recusandae - Vero (B/F/M) (M/F/M)

Non Tempore Tenetur Recusandae - Vero (B/F/M) (M/F/M)

Doloribus : Facere d'quidem.

Itaque v Earum 75010 10z Necessitatibus.

Aute ad omnis : 24/08/2026.

scrapy-w3lib-d6b4a87/tests/benchmarks/test_benchmark_encoding.py000066400000000000000000000153211525715767700251720ustar00rootroot00000000000000from __future__ import annotations from typing import TYPE_CHECKING, Any import pytest from tests.benchmarks import BENCHMARK_MARKS, CasesMapType from w3lib.encoding import ( html_body_declared_encoding, html_to_unicode, http_content_type_encoding, read_bom, resolve_encoding, to_unicode, ) if TYPE_CHECKING: from collections.abc import Callable from pytest_codspeed import BenchmarkFixture # type: ignore[import-not-found] pytestmark = BENCHMARK_MARKS BENCHMARK_CASES: CasesMapType = { read_bom: [ ((b"\xfe\xff\x6c\x34",), {}), ((b"\xff\xfe\x34\x6c",), {}), ((b"\x00\x00\xfe\xff\x00\x00\x6c\x34",), {}), ((b"\xff\xfe\x00\x00\x34\x6c\x00\x00",), {}), ((b"foo",), {}), ((b"",), {}), ], http_content_type_encoding: [ (("Content-Type: text/html; charset=ISO-8859-4",), {}), (("something else",), {}), ], html_body_declared_encoding: [ ( ( b"""""", ), {}, ), ( ( b"""\n""", ), {}, ), ( ( b"""""", ), {}, ), ( ( b"""""", ), {}, ), ( ( b"""""", ), {}, ), ( ( b"""""", ), {}, ), ( ( b""" bad html still supported < meta http-equiv='Content-Type'\n content="text/html; charset=utf-8">""", ), {}, ), ((b"""""",), {}), ((b"""""",), {}), ((b"""""",), {}), ((b"something else",), {}), ( ( b""" this isn't searched """, ), {}, ), ( ( b"""""", ), {}, ), (("something else",), {}), (("""""",), {}), ( ( """ this isn't searched """, ), {}, ), ( ( """""", ), {}, ), ], resolve_encoding: [ (("latin1",), {}), ((" Latin-1",), {}), (("gb_2312-80",), {}), (("unknown encoding",), {}), ], to_unicode: [ ((b"\xc2\xa3", "utf-8"), {}), ((b"\xc2\xc2\xa3", "utf-8"), {}), ], html_to_unicode: [ ( ( "Content-Type: text/html; charset=cp1251", b"\xea\xe8\xf0\xe8\xeb\xeb\xe8\xf7\xe5\xf1\xea\xe8\xe9 \xf2\xe5\xea\xf1\xf2", ), {}, ), (("Content-Type: text/html; charset=utf-8", b"\xc2\xa3"), {}), (("Content-Type: text/html; charset=iso-8859-1", b"\xa3"), {}), (("Content-Type: text/html; charset=", b"\xc2\xa3"), {}), (("Content-Type: text/html; charset=none", b"\xc2\xa3"), {}), (("Content-Type: text/html; charset=gb2312", b"\xa8D"), {}), (("Content-Type: text/html; charset=gbk", b"\xa8D"), {}), (("Content-Type: text/html; charset=big5", b"\xf9\xda"), {}), ( ( "Content-Type: text/html; charset=utf-8", b"\xef\xbb\xbfWORD\xe3\xabWORD2", ), {}, ), ((None, b"\xef\xbb\xbfWORD\xe3\xabWORD2"), {}), (("Content-Type: text/html; charset=utf-8", b"\xef\xbb\xbfWORD\xe3\xab"), {}), ((None, b"\xef\xbb\xbfWORD\xe3\xab"), {}), (("Content-Type: text/html; charset=utf-8", b"PREFIX\xe3\xabSUFFIX"), {}), (("Content-Type: text/html; charset=utf-8", b"\xf0value"), {}), (("Content-Type: text/html; charset=utf-8", b"\xef\xbb\xbfhi"), {}), ((None, b"\xef\xbb\xbfhi"), {}), (("Content-Type: text/html; charset=utf-16", b"\xfe\xff\x00h\x00i"), {}), ((None, b"\xfe\xff\x00h\x00i"), {}), (("Content-Type: text/html; charset=utf-16", b"\xff\xfeh\x00i\x00"), {}), ((None, b"\xff\xfeh\x00i\x00"), {}), ( ( "Content-Type: text/html; charset=utf-32", b"\x00\x00\xfe\xff\x00\x00\x00h\x00\x00\x00i", ), {}, ), ((None, b"\x00\x00\xfe\xff\x00\x00\x00h\x00\x00\x00i"), {}), ( ( None, b"""blah blah < meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> other stuff""", ), {}, ), ( ( "Content-Type: text/html; charset=utf-8", b"""blah blah < meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> other stuff""", ), {}, ), ((None, b"\xef\xbb\xbfblah blah"), {}), ((None, b""""""), {"auto_detect_fun": lambda x: "ascii"}), ((None, b"no encoding info"), {"auto_detect_fun": lambda x: "ascii"}), ((None, b"no encoding info"), {}), ((None, b"no encoding info"), {"default_encoding": "ascii"}), ((None, b""), {}), ], } @pytest.mark.parametrize("func", BENCHMARK_CASES) def test_benchmark_encoding( benchmark: BenchmarkFixture, func: Callable[..., Any], ) -> None: @benchmark def factory(): for args, kwargs in BENCHMARK_CASES[func]: func(*args, **kwargs) @pytest.mark.parametrize("func", BENCHMARK_CASES) def test_benchmark_encoding_cold( benchmark: BenchmarkFixture, func: Callable[..., Any], ) -> None: """Same cases as test_benchmark_encoding but with the resolve_encoding LRU cache cleared before every round.""" def factory(): for args, kwargs in BENCHMARK_CASES[func]: func(*args, **kwargs) benchmark.pedantic(factory, setup=resolve_encoding.cache_clear, rounds=100) scrapy-w3lib-d6b4a87/tests/benchmarks/test_benchmark_html.py000066400000000000000000000231371525715767700243540ustar00rootroot00000000000000from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any import pytest from tests.benchmarks import BENCHMARK_MARKS, CasesMapType from w3lib.html import ( get_base_url, get_meta_refresh, has_entities, remove_comments, remove_tags, remove_tags_with_content, replace_entities, replace_escape_chars, replace_tags, unquote_markup, ) if TYPE_CHECKING: from collections.abc import Callable from pytest_codspeed import BenchmarkFixture # type: ignore[import-not-found] pytestmark = BENCHMARK_MARKS # Real pages, one per way a document can shape the cost of a lookup. In # a sample of 246 pages from 96 popular sites (September 2026), 235 had no # at all, 3 had a without href, and 1 had a in the # head, so the no-base page is the representative workload and the others are # the edge cases worth watching. PAGES = { path.stem: path.read_bytes() for path in sorted((Path(__file__).parent / "pages").glob("*.html")) } BENCHMARK_CASES: CasesMapType = { replace_entities: [ ((b"no entities",), {}), ((b"Price: £100!",), {}), (("no entities",), {}), (("Price: £100!",), {}), (("As low as £100!",), {}), ((b"As low as £100!",), {}), ( ( "redirectTo=search&searchtext=MR0221Y&aff=buyat&affsrc=d_data&cm_mmc=buyat-_-ELECTRICAL & SEASONAL-_-MR0221Y-_-9-carat gold ½oz solid crucifix pendant", ), {}, ), ((b"Low < High & Medium £ six",), {"keep": ["lt", "amp"]}), (("Low < High & Medium £ six",), {"keep": ["lt", "amp"]}), (("a < b &illegal; c � six",), {"remove_illegal": False}), (("a < b &illegal; c � six",), {"remove_illegal": True}), (("x≤y",), {}), (("xy",), {}), (("xy",), {"remove_illegal": False}), (("�",), {}), (("�",), {"remove_illegal": False}), (("x™y",), {"encoding": "cp1252"}), (("x™y",), {"encoding": "cp1252"}), (("x\x99™™y",), {"encoding": "cp1252"}), (("<<!",), {"encoding": "cp1252"}), (("<!",), {"encoding": "cp1252"}), (("A ",), {"encoding": "cp1252"}), (("A!",), {"encoding": "cp1252"}), (("Ah",), {"encoding": "cp1252"}), (("A!",), {"encoding": "cp1252"}), (("Ax",), {"encoding": "cp1252"}), (("³!",), {"encoding": "cp1252"}), (("Á!",), {"encoding": "cp1252"}), (("☃!",), {"encoding": "cp1252"}), (("™",), {"encoding": "cp1252"}), (("™",), {"encoding": "cp1252"}), ], replace_tags: [ ((b"no entities",), {}), (("no entities",), {}), (("This text contains some tag",), {}), ((b"This text is very important", " "), {}), ((b'Click here',), {}), ], remove_comments: [ ((b"without comments",), {}), ((b"",), {}), (("without comments",), {}), (("",), {}), (("text without comments",), {}), (("",), {}), (("Hello",), {}), (("Hello",), {}), ((b"test whatever",), {}), ((b"test whatever",), {}), ((b"test ') is None assert ( html_body_declared_encoding(b'') == "utf-8" ) @pytest.mark.parametrize( ("body", "expected"), [ # a "charset=" inside an unrelated attribute value is not a # declaration, and neither is the tail of another attribute's name ( b'', None, ), (b'', None), ( b'', "utf-8", ), ( b'', "utf-8", ), # a charset inside a content attribute needs the http-equiv # pragma, however the pragma is spelled, but with a value (b'', None), (b'', None), ( b'', "gb18030", ), # another pragma is not the content-type one, however its own # content value spells "charset=" (b'', None), ( b'', None, ), ( b'', None, ), # only the first content attribute of a tag is read, and an empty # charset attribute does not hide it ( b'', "gb18030", ), ( b'', "gb18030", ), # a charset attribute wins over a content one, wherever it is ( b'', "utf-8", ), # a quoted ">" does not end the tag, and a quoted tag written # inside one neither ends nor stops the scan (b'', "utf-8"), (b'', "utf-8"), # an empty charset attribute is not a declaration (b'', None), (b'', "utf-8"), # a quoted "a charset="big5">', None), (b'>', "big5hkscs"), # an unterminated comment hides everything after it (b'"), str) assert isinstance(remove_comments("without comments"), str) assert isinstance(remove_comments(""), str) def test_no_comments(self): # text without comments assert remove_comments("text without comments") == "text without comments" def test_remove_comments(self): # text with comments assert remove_comments("") == "" assert remove_comments("Hello") == "Hello" assert remove_comments("Hello") == "Hello" assert remove_comments(b"test whatever") == "test whatever" assert ( remove_comments(b"test whatever") == "test whatever" ) assert remove_comments(b"test """) == "" assert get_base_url(""" """ ) == "http://example_2.com/" ) assert ( get_base_url( """ """ ) == "http://example_3.com/" ) def test_base_url_in_script(self): baseurl = "https://example.org" # A browser does not parse tags inside """, baseurl, ) == "https://example.org" ) assert ( get_base_url( """""", baseurl, ) == "https://example.org" ) # a real after the ignored one is still picked up assert ( get_base_url( """""" """""", baseurl, ) == "http://example.org/found/" ) # an unterminated " ) assert get_meta_refresh(body, baseurl) == (None, None) def test_unterminated_ignored_tag(self): # an unterminated """ assert get_meta_refresh(body, baseurl) == (None, None) assert get_meta_refresh(body, baseurl, ignore_tags=()) == ( 0.0, "http://example.org/foobar_required", ) def test_redirections_in_different_ordering__in_meta_tag(self): baseurl = "http://localhost:8000" url1 = '' url2 = '' assert get_meta_refresh(url1, baseurl) == ( 0.0, "http://localhost:8000/dummy.html", ) assert get_meta_refresh(url2, baseurl) == ( 0.0, "http://localhost:8000/dummy.html", ) @pytest.mark.parametrize( "body", [ '', '', '', '', '', "", ], ) def test_attribute_containing_the_substring_content(self, body: str) -> None: assert get_meta_refresh(body, "http://example.org") == ( 3.0, "http://example.org/next", ) def test_first_content_attribute_with_a_payload_wins(self) -> None: baseurl = "http://example.org" body = '' assert get_meta_refresh(body, baseurl) == (3.0, "http://example.org/next") def test_http_equiv_without_refresh(self) -> None: # "refresh" elsewhere in the tag gets it scanned, but the pragma is # only the http-equiv attribute with refresh in its value baseurl = "http://example.org" body = '' assert get_meta_refresh(body, baseurl) == (None, None) body = '' assert get_meta_refresh(body, baseurl) == (3.0, "http://example.org/next") def test_unquoted_whitespace(self) -> None: body = "" assert get_meta_refresh(body, "http://example.org") == (None, None) def test_no_catastrophic_backtracking(self) -> None: # a long run of whitespace inside a refresh tag must be skipped in # one step, not retried from every position evil = '", "http://example.org") == (None, None) assert get_meta_refresh( evil + 'content="3; url=/next">', "http://example.org" ) == (3.0, "http://example.org/next") assert time.process_time() - start < 2 def test_non_refresh_meta_is_skipped(self): baseurl = "http://example.org" body = """ """ assert get_meta_refresh(body, baseurl) == ( 2.0, "http://example.org/next", ) @pytest.mark.parametrize( ("encoding", "char"), [ ("utf-8", "\u793e"), ("latin-1", "\u00e9"), ("shift_jis", "\u793e"), ("gb18030", "\u793e"), ("iso2022_jp", "\u793e"), ], ) def test_get_meta_refresh_bytes(self, encoding: str, char: str) -> None: baseurl = "http://example.org" with_refresh = ( f"{char}" "" ) without_refresh = f"{char}" assert ( get_meta_refresh(with_refresh.encode(encoding), baseurl, encoding) == get_meta_refresh(with_refresh, baseurl, encoding) == (3.0, "http://example.org/next") ) assert ( get_meta_refresh(without_refresh.encode(encoding), baseurl, encoding) == get_meta_refresh(without_refresh, baseurl, encoding) == (None, None) ) def test_get_meta_refresh_spelled_by_characters(self) -> None: # These kanji encode to bytes that spell "refresh", which neither a # browser nor the scan of the decoded document sees. text = "

\u9c5a\u80d9\u7e89\u8515

" assert text.encode("iso2022_jp") == b"

\x1b$Brefreshx\x1b(B

" assert get_meta_refresh( text.encode("iso2022_jp"), "http://example.org", "iso2022_jp" ) == (None, None) def test_get_meta_refresh_non_ascii_compatible(self) -> None: # UTF-16 writes ASCII characters as something else than their ASCII # bytes, so the document is decoded before it is scanned. body = "" assert get_meta_refresh( body.encode("utf-16"), "http://example.org", "utf-16" ) == get_meta_refresh(body, "http://example.org", "utf-16") def test_get_meta_refresh_split_by_a_dropped_escape(self) -> None: # ESC ( B redesignates ASCII where ASCII is already in use, so it # divides the tag in the bytes but not in the document. raw = b'' assert ( raw.decode("iso2022_jp") == '' ) assert get_meta_refresh(raw, "http://example.org", "iso2022_jp") == ( 3.0, "http://example.org/next", ) def test_get_meta_refresh_non_ascii_whitespace(self) -> None: # U+3000 does not separate a tag name from its attributes. body = "" assert get_meta_refresh(body, "http://example.org") == (None, None) assert get_meta_refresh(body.encode(), "http://example.org") == (None, None) def test_get_meta_refresh_content_non_ascii_whitespace(self) -> None: # The refresh content is parsed with ASCII whitespace only, so U+00A0 # around the interval or the ";" leaves it unparsed and no redirect is # reported, as a browser reloads the same document instead. for content in (" 0;url=/next", "0 ;url=/next", "0; url=/next"): body = f"" assert get_meta_refresh(body, "http://example.org") == (None, None) # An ASCII-whitespace variant is still parsed. assert get_meta_refresh( "", "http://example.org" ) == (0.0, "http://example.org/next") def test_get_meta_refresh_non_ascii_case_folding(self) -> None: # U+017F uppercases to "S", but it is no "s" in a tag name, so this is # no ", '

', '

', "a < b", "a > b", "<", ">", "x", ] def base(text: str | bytes, **kwargs: object) -> object: return get_base_url(text, "https://example.org", **kwargs) # type: ignore[arg-type] def meta(text: str | bytes, **kwargs: object) -> object: return get_meta_refresh(text, "https://example.org", **kwargs) # type: ignore[arg-type] @pytest.mark.parametrize( ("func", "tag", "found", "missing"), [ (base, BASE_TAG, "http://example.org/found", "https://example.org"), (meta, META_TAG, (5, "http://example.org/found"), (None, None)), ], ids=["base", "meta"], ) class TestMaxScan: def test_straddling_tag(self, func, tag, found, missing): # A tag that starts before the limit and ends after it is read whole, # wherever in it the limit falls, inside a quoted value included. for offset in range(1, len(tag)): text = "a" * (LIMIT - offset) + tag assert func(text, max_scan=LIMIT) == found assert func(text.encode(), max_scan=LIMIT) == found def test_before_limit(self, func, tag, found, missing): assert func(tag + "a" * LIMIT, max_scan=LIMIT) == found def test_unterminated_tag_within_limit(self, func, tag, found, missing): assert func(tag[:-1], max_scan=LIMIT) == found def test_stray_lt_before_limit(self, func, tag, found, missing): # A "<" that starts no tag must not extend the scan past the limit. assert func("1 < 2 " + "a" * LIMIT + tag, max_scan=LIMIT) == missing def test_bytes_limit_counts_bytes(self, func, tag, found, missing): # The limit reaches the tag in characters, but not in bytes. text = "\u00e9" * 20 + tag assert func(text, max_scan=30) == found assert func(text.encode(), max_scan=30) == missing def test_bytes_split_character(self, func, tag, found, missing): # The cut splits the last character, which decoding replaces. assert func(("\u00e9" * 5).encode() + tag.encode(), max_scan=9) == missing @given( markup=st.lists(st.sampled_from(FRAGMENTS), max_size=12).map("".join), max_scan=st.integers(min_value=0, max_value=400), ) def test_cut_never_invents(self, func, tag, found, missing, markup, max_scan): # A cut can misread an angle bracket in a comment or an attribute value # only into looking at less, never into a result of its own. assert func(markup, max_scan=max_scan) in (func(markup), missing) assert func(markup.encode(), max_scan=max_scan) in (func(markup), missing) def test_reading_on_stops_at_the_next_tag(self, func, tag, found, missing): # Reading a split tag to its end stops where the next tag begins. assert func("

None: # Reading half a tag would yield a redirect to a truncated url, and the # quoted ">" hides where the tag ends from anything that reads one # differently from the scan. tag = '' assert get_meta_refresh(tag, "https://example.org", max_scan=cut) in ( (None, None), (5.0, "http://example.org/found"), ) scrapy-w3lib-d6b4a87/tests/test_http.py000066400000000000000000000056751525715767700202470ustar00rootroot00000000000000from collections import OrderedDict from w3lib.http import ( HeadersDictInput, basic_auth_header, headers_dict_to_raw, headers_raw_to_dict, ) class TestHttp: def test_basic_auth_header(self): assert ( basic_auth_header("someuser", "somepass") == b"Basic c29tZXVzZXI6c29tZXBhc3M=" ) # Check url unsafe encoded header assert ( basic_auth_header("someuser", "@&o?Q") == b"Basic c29tZXVzZXI6QDx5dTk+Jm8/UQ==" ) def test_basic_auth_header_encoding(self): assert ( basic_auth_header("somæusèr", "sømepäss", encoding="utf8") == b"Basic c29tw6Z1c8Oocjpzw7htZXDDpHNz" ) # default encoding (ISO-8859-1) assert ( basic_auth_header("somæusèr", "sømepäss") == b"Basic c29t5nVz6HI6c/htZXDkc3M=" ) def test_headers_raw_dict_none(self): assert headers_raw_to_dict(None) is None assert headers_dict_to_raw(None) is None def test_headers_raw_dict_empty(self): assert headers_raw_to_dict(b"") == {} assert headers_dict_to_raw({}) == b"" def test_headers_raw_to_dict(self): raw = b"Content-type: text/html\n\rAccept: gzip\n\r\ Cache-Control: no-cache\n\rCache-Control: no-store\n\n" dct = { b"Content-type": [b"text/html"], b"Accept": [b"gzip"], b"Cache-Control": [b"no-cache", b"no-store"], } assert headers_raw_to_dict(raw) == dct def test_headers_dict_to_raw(self): dct = OrderedDict([(b"Content-type", b"text/html"), (b"Accept", b"gzip")]) assert headers_dict_to_raw(dct) == b"Content-type: text/html\r\nAccept: gzip" def test_headers_dict_to_raw_listtuple(self): dct: HeadersDictInput = OrderedDict( [(b"Content-type", [b"text/html"]), (b"Accept", [b"gzip"])] ) assert headers_dict_to_raw(dct) == b"Content-type: text/html\r\nAccept: gzip" dct = OrderedDict([(b"Content-type", (b"text/html",)), (b"Accept", (b"gzip",))]) assert headers_dict_to_raw(dct) == b"Content-type: text/html\r\nAccept: gzip" dct = OrderedDict([(b"Cookie", (b"val001", b"val002")), (b"Accept", b"gzip")]) assert ( headers_dict_to_raw(dct) == b"Cookie: val001\r\nCookie: val002\r\nAccept: gzip" ) dct = OrderedDict([(b"Cookie", [b"val001", b"val002"]), (b"Accept", b"gzip")]) assert ( headers_dict_to_raw(dct) == b"Cookie: val001\r\nCookie: val002\r\nAccept: gzip" ) def test_headers_dict_to_raw_wrong_values(self): dct: HeadersDictInput = OrderedDict( [ (b"Content-type", 0), ] ) assert headers_dict_to_raw(dct) == b"" dct = OrderedDict([(b"Content-type", 1), (b"Accept", [b"gzip"])]) assert headers_dict_to_raw(dct) == b"Accept: gzip" scrapy-w3lib-d6b4a87/tests/test_url.py000066400000000000000000003015371525715767700200660ustar00rootroot00000000000000from __future__ import annotations import os import sys from inspect import isclass from pathlib import Path from typing import TYPE_CHECKING from urllib.parse import ( parse_qs, parse_qsl, quote, quote_plus, unquote_to_bytes, urlparse, urlsplit, urlunparse, urlunsplit, ) import pytest from hypothesis import HealthCheck, assume, example, given, settings, strategies as st from hypothesis.provisional import urls as hyp_urls from w3lib._infra import ( _ASCII_ALPHA, _ASCII_ALPHANUMERIC, _ASCII_TAB_OR_NEWLINE, _C0_CONTROL_OR_SPACE, ) from w3lib._url import ( _SPECIAL_SCHEMES, _parse_qs, _parse_qsl, _quote, _split_params, _unquote, _unquote_plus, _urlparse, _urlsplit, _urlunparse, _urlunsplit, ) from w3lib.url import ( _normalize_ipv6_host, _remove_dot_segments, add_http_if_no_scheme, add_or_replace_parameter, add_or_replace_parameters, any_to_uri, canonicalize_url, file_uri_to_path, is_url, parse_data_uri, parse_qsl_to_bytes, parse_url, path_to_file_uri, safe_download_url, safe_url_string, url_query_cleaner, url_query_parameter, ) if TYPE_CHECKING: from collections.abc import Callable # Test cases for URL-to-safe-URL conversions with a URL and an encoding as # input parameters. # # (encoding, input URL, output URL or exception) SAFE_URL_ENCODING_CASES: list[tuple[str | None, str | bytes, str | type[Exception]]] = [ (None, "", ValueError), (None, "https://example.com", "https://example.com"), (None, "https://example.com/©", "https://example.com/%C2%A9"), # Paths are always UTF-8-encoded. ("iso-8859-1", "https://example.com/©", "https://example.com/%C2%A9"), # Queries are UTF-8-encoded if the scheme is not special, ws or wss. ("iso-8859-1", "a://example.com?©", "a://example.com?%C2%A9"), *( ("iso-8859-1", f"{scheme}://example.com?©", f"{scheme}://example.com/?%C2%A9") for scheme in ("ws", "wss") ), *( ("iso-8859-1", f"{scheme}://example.com?©", f"{scheme}://example.com/?%A9") for scheme in _SPECIAL_SCHEMES if scheme not in {"ws", "wss"} ), # Fragments are always UTF-8-encoded. ("iso-8859-1", "https://example.com#©", "https://example.com#%C2%A9"), ] INVALID_SCHEME_FOLLOW_UPS = "".join( chr(value) for value in range(0x81) if ( chr(value) not in _ASCII_ALPHANUMERIC and chr(value) not in "+-." and chr(value) not in _C0_CONTROL_OR_SPACE # stripped and chr(value) != ":" # separator ) ) SAFE_URL_URL_INVALID_SCHEME_CASES = tuple( (f"{scheme}://example.com", ValueError) for scheme in ( # A scheme is required. "", # The first scheme letter must be an ASCII alpha. # Note: 0x80 is included below to also test non-ASCII example. *( chr(value) for value in range(0x81) if ( chr(value) not in _ASCII_ALPHA and chr(value) not in _C0_CONTROL_OR_SPACE # stripped and chr(value) != ":" # separator ) ), # The follow-up scheme letters can also be ASCII numbers, plus, hyphen, # or period. f"a{INVALID_SCHEME_FOLLOW_UPS}", ) ) SCHEME_NON_FIRST = _ASCII_ALPHANUMERIC + "+-." # Username and password characters that do not need escaping. # Removed for RFC 2396 and RFC 3986: % # Removed for the URL living standard: :;= USERINFO_SAFE = _ASCII_ALPHANUMERIC + "-_.!~*'()" + "&+$," USERNAME_TO_ENCODE = "".join( chr(value) for value in range(0x80) if ( chr(value) not in _C0_CONTROL_OR_SPACE and chr(value) not in USERINFO_SAFE and chr(value) not in ":/?#\\[]" ) ) USERNAME_ENCODED = "".join(f"%{ord(char):02X}" for char in USERNAME_TO_ENCODE) PASSWORD_TO_ENCODE = USERNAME_TO_ENCODE + ":" PASSWORD_ENCODED = "".join(f"%{ord(char):02X}" for char in PASSWORD_TO_ENCODE) # Path characters that do not need escaping. # Removed for RFC 2396 and RFC 3986: %[\]^| PATH_SAFE = _ASCII_ALPHANUMERIC + "-_.!~*'()" + ":@&=+$," + "/" + ";" PATH_TO_ENCODE = "".join( chr(value) for value in range(0x80) if ( chr(value) not in _C0_CONTROL_OR_SPACE and chr(value) not in PATH_SAFE and chr(value) not in "?#\\" ) ) PATH_ENCODED = "".join(f"%{ord(char):02X}" for char in PATH_TO_ENCODE) # Query characters that do not need escaping. # Removed for RFC 2396 and RFC 3986: %[\]^`{|} # Removed for the URL living standard: ' (special) QUERY_SAFE = _ASCII_ALPHANUMERIC + "-_.!~*'()" + ":@&=+$," + "/" + ";" + "?" QUERY_TO_ENCODE = "".join( chr(value) for value in range(0x80) if ( chr(value) not in _C0_CONTROL_OR_SPACE and chr(value) not in QUERY_SAFE and chr(value) != "#" ) ) QUERY_ENCODED = "".join(f"%{ord(char):02X}" for char in QUERY_TO_ENCODE) SPECIAL_QUERY_SAFE = QUERY_SAFE.replace("'", "") SPECIAL_QUERY_TO_ENCODE = "".join( chr(value) for value in range(0x80) if ( chr(value) not in _C0_CONTROL_OR_SPACE and chr(value) not in SPECIAL_QUERY_SAFE and chr(value) != "#" ) ) SPECIAL_QUERY_ENCODED = "".join(f"%{ord(char):02X}" for char in SPECIAL_QUERY_TO_ENCODE) # Fragment characters that do not need escaping. # Removed for RFC 2396 and RFC 3986: #%[\\]^{|} FRAGMENT_SAFE = _ASCII_ALPHANUMERIC + "-_.!~*'()" + ":@&=+$," + "/" + ";" + "?" FRAGMENT_TO_ENCODE = "".join( chr(value) for value in range(0x80) if (chr(value) not in _C0_CONTROL_OR_SPACE and chr(value) not in FRAGMENT_SAFE) ) FRAGMENT_ENCODED = "".join(f"%{ord(char):02X}" for char in FRAGMENT_TO_ENCODE) # Test cases for URL-to-safe-URL conversions with only a URL as input parameter # (i.e. no encoding or base URL). # # (input URL, output URL or exception) SAFE_URL_URL_CASES = ( # Invalid input type (1, Exception), (object(), Exception), # Empty string ("", ValueError), # Remove any leading and trailing C0 control or space from input. *( (f"{char}https://example.com{char}", "https://example.com") for char in _C0_CONTROL_OR_SPACE if char not in _ASCII_TAB_OR_NEWLINE ), # Remove all ASCII tab or newline from input. ( ( f"{_ASCII_TAB_OR_NEWLINE}h{_ASCII_TAB_OR_NEWLINE}ttps" f"{_ASCII_TAB_OR_NEWLINE}:{_ASCII_TAB_OR_NEWLINE}/" f"{_ASCII_TAB_OR_NEWLINE}/{_ASCII_TAB_OR_NEWLINE}a" f"{_ASCII_TAB_OR_NEWLINE}b{_ASCII_TAB_OR_NEWLINE}:" f"{_ASCII_TAB_OR_NEWLINE}a{_ASCII_TAB_OR_NEWLINE}b" f"{_ASCII_TAB_OR_NEWLINE}@{_ASCII_TAB_OR_NEWLINE}exam" f"{_ASCII_TAB_OR_NEWLINE}ple.com{_ASCII_TAB_OR_NEWLINE}:" f"{_ASCII_TAB_OR_NEWLINE}1{_ASCII_TAB_OR_NEWLINE}2" f"{_ASCII_TAB_OR_NEWLINE}/{_ASCII_TAB_OR_NEWLINE}a" f"{_ASCII_TAB_OR_NEWLINE}b{_ASCII_TAB_OR_NEWLINE}?" f"{_ASCII_TAB_OR_NEWLINE}a{_ASCII_TAB_OR_NEWLINE}b" f"{_ASCII_TAB_OR_NEWLINE}#{_ASCII_TAB_OR_NEWLINE}a" f"{_ASCII_TAB_OR_NEWLINE}b{_ASCII_TAB_OR_NEWLINE}" ), "https://ab:ab@example.com:12/ab?ab#ab", ), # Scheme (f"{_ASCII_ALPHA}://example.com", f"{_ASCII_ALPHA.lower()}://example.com"), ( f"a{SCHEME_NON_FIRST}://example.com", f"a{SCHEME_NON_FIRST.lower()}://example.com", ), *SAFE_URL_URL_INVALID_SCHEME_CASES, # Authority ("https://a@example.com", "https://a@example.com"), ("https://a:@example.com", "https://a:@example.com"), ("https://:a@example.com", "https://:a@example.com"), ("https://a:a@example.com", "https://a:a@example.com"), ("https://a%3A@example.com", "https://a%3A@example.com"), ( f"https://{USERINFO_SAFE}:{USERINFO_SAFE}@example.com", f"https://{USERINFO_SAFE}:{USERINFO_SAFE}@example.com", ), ( f"https://{USERNAME_TO_ENCODE}:{PASSWORD_TO_ENCODE}@example.com", f"https://{USERNAME_ENCODED}:{PASSWORD_ENCODED}@example.com", ), ("https://@\\example.com", ValueError), # "\" ends the authority of a special-scheme URL, so a "\" before "@" is # not a userinfo separator: the host is what precedes the "\". ("https://evil.com\\@good.com/", "https://evil.com/@good.com/"), ("https://good.com\\@evil.com/", "https://good.com/@evil.com/"), ("https://\x80:\x80@example.com", "https://%C2%80:%C2%80@example.com"), # Host ("https://example.com", "https://example.com"), ("https://.example", "https://.example"), ("https://\x80.example", ValueError), ("https://%80.example", ValueError), # The 4 cases below test before and after crossing DNS length limits on # domain name labels (63 characters) and the domain name as a whole (253 # characters). However, all cases are expected to pass because the URL # living standard does not require domain names to be within these limits. (f"https://{'a' * 63}.example", f"https://{'a' * 63}.example"), (f"https://{'a' * 64}.example", f"https://{'a' * 64}.example"), ( f"https://{'a' * 63}.{'a' * 63}.{'a' * 63}.{'a' * 53}.example", f"https://{'a' * 63}.{'a' * 63}.{'a' * 63}.{'a' * 53}.example", ), ( f"https://{'a' * 63}.{'a' * 63}.{'a' * 63}.{'a' * 54}.example", f"https://{'a' * 63}.{'a' * 63}.{'a' * 63}.{'a' * 54}.example", ), ("https://ñ.example", "https://xn--ida.example"), ("http://192.168.0.0", "http://192.168.0.0"), ("http://192.168.0.256", ValueError), ("http://192.168.0.0.0", ValueError), ("http://[2a01:5cc0:1:2::4]", "http://[2a01:5cc0:1:2::4]"), ("http://[2a01:5cc0:1:2:3:4]", ValueError), ("https://[2402:4e00:40:40::2:3b6]", "https://[2402:4e00:40:40::2:3b6]"), ("https://[2402:4e00:40:40::2:3b6]:443", "https://[2402:4e00:40:40::2:3b6]:443"), ("http://[::1]", "http://[::1]"), ("http://[::1]:8080/path?q=1", "http://[::1]:8080/path?q=1"), # checknetloc, the most of the cases are copied from # https://github.com/python/cpython/blob/main/Lib/test/test_urlparse.py ("http://[v6a.ip]", "http://v6a.ip"), # IPv4-in-brackets / invalid host syntax ("Scheme://user@[192.0.2.146]/Path?Query", ValueError), ("Scheme://user@[important.com:8000]/Path?Query", ValueError), ("Scheme://user@[v123r.IP]/Path?Query", ValueError), ("Scheme://user@[v12ae]/Path?Query", ValueError), ("Scheme://user@[v.IP]/Path?Query", ValueError), ("Scheme://user@[v123.]/Path?Query", ValueError), ("Scheme://user@[v]/Path?Query", ValueError), # invalid IPv6-like malformed forms ("Scheme://user@[0439:23af::2309::fae7:1234]/Path?Query", ValueError), ( "Scheme://user@[0439:23af:2309::fae7:1234:2342:438e:192.0.2.146]/Path?Query", ValueError, ), # stray bracket placement / malformed bracketed host ("Scheme://user@]v6a.ip[/Path", ValueError), ("scheme://prefix.[v6a.ip]", ValueError), ("scheme://[v6a.ip].suffix", ValueError), ("scheme://prefix.[v6a.ip]/", ValueError), ("scheme://[v6a.ip].suffix/", ValueError), ("scheme://prefix.[v6a.ip]?", ValueError), ("scheme://[v6a.ip].suffix?", ValueError), # IPv6 label misuse in DNS-like context ("scheme://prefix.[::1]", ValueError), ("scheme://[::1].suffix", ValueError), ("scheme://prefix.[::1]/", ValueError), ("scheme://[::1].suffix/", ValueError), ("scheme://prefix.[::1]?", ValueError), ("scheme://[::1].suffix?", ValueError), # invalid port-like suffixes on IPv6-ish host context ("scheme://prefix.[::1]:a", ValueError), ("scheme://[::1].suffix:a", ValueError), ("scheme://prefix.[::1]:a1", ValueError), ("scheme://[::1].suffix:a1", ValueError), ("scheme://prefix.[::1]:1a", ValueError), ("scheme://[::1].suffix:1a", ValueError), ("scheme://prefix.[::1]:", ValueError), ("scheme://[::1].suffix:/", ValueError), ("scheme://prefix.[::1]:?", ValueError), # userinfo with invalid host embedding ("scheme://user@prefix.[v6a.ip]", ValueError), ("scheme://user@[v6a.ip].suffix", ValueError), # brackets confined to the userinfo, leaving a plain host ("scheme://us[er]@example.com", ValueError), ("scheme://us[er]@[::1]", "scheme://us%5Ber%5D@[::1]"), # unmatched / broken bracket structures ("scheme://[v6a.ip", ValueError), ("scheme://v6a.ip]", ValueError), ("scheme://]v6a.ip[", ValueError), ("scheme://]v6a.ip", ValueError), ("scheme://v6a.ip[", ValueError), # dot/bracket mixed malformed host patterns ("scheme://prefix.[v6a.ip", ValueError), ("scheme://v6a.ip].suffix", ValueError), ("scheme://prefix]v6a.ip[suffix", ValueError), ("scheme://prefix]v6a.ip", ValueError), ("scheme://v6a.ip[suffix", ValueError), # Port ("https://example.com:", "https://example.com:"), ("https://example.com:1", "https://example.com:1"), ("https://example.com:443", "https://example.com:443"), ("https://example.com:bad_port", ValueError), ("https://example.com:-1", ValueError), ("https://example.com:66000", ValueError), ("https://example.com:8_0", ValueError), ("https://example.com:+80", ValueError), ("https://example.com:٨٠", ValueError), # Path ("https://example.com/", "https://example.com/"), ("https://example.com/a", "https://example.com/a"), ("https://example.com\\a", "https://example.com/a"), ("https://example.com/a\\b", "https://example.com/a/b"), # "\" is only converted to "/" before the query/fragment; inside them it # is percent-encoded as usual. ("https://example.com\\a?b\\c", "https://example.com/a?b%5Cc"), ("https://example.com\\a#b\\c", "https://example.com/a#b%5Cc"), ("https://example.com\\a?b\\c#d\\e", "https://example.com/a?b%5Cc#d%5Ce"), ("https://example.com\\a#b?c\\d", "https://example.com/a#b?c%5Cd"), ( f"https://example.com/{PATH_SAFE}", f"https://example.com/{PATH_SAFE}", ), ( f"https://example.com/{PATH_TO_ENCODE}", f"https://example.com/{PATH_ENCODED}", ), ("https://example.com/ñ", "https://example.com/%C3%B1"), ("https://example.com/ñ%C3%B1", "https://example.com/%C3%B1%C3%B1"), # safe unquoted ("https://example.com/%3F", "https://example.com/%3F"), ("https://example.com/%23", "https://example.com/%23"), # Query ("https://example.com?", "https://example.com?"), ("https://example.com/?", "https://example.com/?"), ("https://example.com?a", "https://example.com/?a"), ("https://example.com?a=", "https://example.com/?a="), ("https://example.com?a=b", "https://example.com/?a=b"), ( f"a://example.com?{QUERY_SAFE}", f"a://example.com?{QUERY_SAFE}", ), ( f"a://example.com?{QUERY_TO_ENCODE}", f"a://example.com?{QUERY_ENCODED}", ), *( ( f"{scheme}://example.com?{SPECIAL_QUERY_SAFE}", f"{scheme}://example.com/?{SPECIAL_QUERY_SAFE}", ) for scheme in _SPECIAL_SCHEMES ), *( ( f"{scheme}://example.com?{SPECIAL_QUERY_TO_ENCODE}", f"{scheme}://example.com/?{SPECIAL_QUERY_ENCODED}", ) for scheme in _SPECIAL_SCHEMES ), ("https://example.com?ñ", "https://example.com/?%C3%B1"), ("https://example.com?ñ%C3%B1", "https://example.com/?%C3%B1%C3%B1"), # Fragment ("https://example.com#", "https://example.com#"), ("https://example.com/#", "https://example.com/#"), ("https://example.com?#", "https://example.com?#"), ("https://example.com/?#", "https://example.com/?#"), ("https://example.com#a", "https://example.com#a"), ( f"a://example.com#{FRAGMENT_SAFE}", f"a://example.com#{FRAGMENT_SAFE}", ), ( f"a://example.com#{FRAGMENT_TO_ENCODE}", f"a://example.com#{FRAGMENT_ENCODED}", ), ("https://example.com#ñ", "https://example.com#%C3%B1"), ("https://example.com#ñ%C3%B1", "https://example.com#%C3%B1%C3%B1"), # All fields, UTF-8 wherever possible. ( "https://ñ:ñ@ñ.example:1/ñ?ñ#ñ", "https://%C3%B1:%C3%B1@xn--ida.example:1/%C3%B1?%C3%B1#%C3%B1", ), # invalid characters after NFKC normalisation ("https://example\uff1a80.com", ValueError), ("https://example\uff03.com", ValueError), ("https://example\uff1f.com", ValueError), ("https://example\uff20.com", ValueError), # "\" ends the authority of a special-scheme URL, and both of these # normalise to "\" under NFKC, so they must be rejected like the others. ("https://evil.com\uff3c.example.com", ValueError), ("https://evil.com\ufe68.example.com", ValueError), # changed after NFKC normalisation ("https://example.com", "https://example.com"), # "[" and "]" outside the authority are ordinary characters and must not # be treated as IPv6 host delimiters. ("https://example.com/[x]", "https://example.com/%5Bx%5D"), ("https://example.com/a]b", "https://example.com/a%5Db"), ("http://example.com/search?tags[]=a", "http://example.com/search?tags%5B%5D=a"), ("https://example.com/a#f[1]", "https://example.com/a#f%5B1%5D"), ("http://[::1]:8080/p?q=[1]", "http://[::1]:8080/p?q=%5B1%5D"), ) def _test_safe_url_func( url: str | bytes, *, encoding: str | None = None, output: str | type[Exception], func: Callable[..., str], ) -> None: kwargs = {} if encoding is not None: kwargs["encoding"] = encoding if isclass(output) and issubclass(output, Exception): with pytest.raises(output): func(url, **kwargs) return actual = func(url, **kwargs) assert actual == output assert func(actual, **kwargs) == output # Idempotency def _test_safe_url_string( url: str | bytes, *, encoding: str | None = None, output: str | type[Exception], ) -> None: return _test_safe_url_func( url, encoding=encoding, output=output, func=safe_url_string, ) KNOWN_SAFE_URL_STRING_ENCODING_ISSUES = { (None, ""), # Invalid URL # UTF-8 encoding is not enforced in non-special URLs, or in URLs with the # ws or wss schemas. ("iso-8859-1", "a://example.com?\xa9"), ("iso-8859-1", "ws://example.com?\xa9"), ("iso-8859-1", "wss://example.com?\xa9"), # UTF-8 encoding is not enforced on the fragment. ("iso-8859-1", "https://example.com#\xa9"), } @pytest.mark.parametrize( ("encoding", "url", "output"), [ ( case if case[:2] not in KNOWN_SAFE_URL_STRING_ENCODING_ISSUES else pytest.param(*case, marks=pytest.mark.xfail(strict=True)) ) for case in SAFE_URL_ENCODING_CASES ], ) def test_safe_url_string_encoding( encoding: str | None, url: str | bytes, output: str | type[Exception] ) -> None: _test_safe_url_string(url, encoding=encoding, output=output) KNOWN_SAFE_URL_STRING_URL_ISSUES = { "", # Invalid URL *(case[0] for case in SAFE_URL_URL_INVALID_SCHEME_CASES), # Userinfo characters that the URL living standard requires escaping (:;=) # are not escaped. "https://@\\example.com", # Invalid URL "https://\x80.example", # Invalid domain name (non-visible character) "https://%80.example", # Invalid domain name (non-visible character) "http://192.168.0.256", # Invalid IP address "http://192.168.0.0.0", # Invalid IP address / domain name "https://example.com:", # Removes the : # Some path characters that RFC 2396 and RFC 3986 require escaping (%) # are not escaped. f"https://example.com/{PATH_TO_ENCODE}", # ? is removed "https://example.com?", "https://example.com/?", # Some query characters that RFC 2396 and RFC 3986 require escaping (%) # are not escaped. f"a://example.com?{QUERY_TO_ENCODE}", # Some special query characters that RFC 2396 and RFC 3986 require escaping # (%) are not escaped. *( f"{scheme}://example.com?{SPECIAL_QUERY_TO_ENCODE}" for scheme in _SPECIAL_SCHEMES ), # ? and # are removed "https://example.com#", "https://example.com/#", "https://example.com?#", "https://example.com/?#", # Some fragment characters that RFC 2396 and RFC 3986 require escaping # (%) are not escaped. f"a://example.com#{FRAGMENT_TO_ENCODE}", } @pytest.mark.parametrize( ("url", "output"), [ ( case if case[0] not in KNOWN_SAFE_URL_STRING_URL_ISSUES else pytest.param(*case, marks=pytest.mark.xfail(strict=True)) ) for case in SAFE_URL_URL_CASES ], ) def test_safe_url_string_url(url: str | bytes, output: str | type[Exception]) -> None: _test_safe_url_string(url, output=output) class TestUrl: def test_safe_url_string(self): # Motoko Kusanagi (Cyborg from Ghost in the Shell) motoko = "\u8349\u8599 \u7d20\u5b50" # note the %20 for space assert safe_url_string(motoko) == "%E8%8D%89%E8%96%99%20%E7%B4%A0%E5%AD%90" assert safe_url_string(motoko) == safe_url_string(safe_url_string(motoko)) # copyright symbol assert safe_url_string("©") == "%C2%A9" # page-encoding does not affect URL path assert safe_url_string("©", "iso-8859-1") == "%C2%A9" # path_encoding does assert safe_url_string("©", path_encoding="iso-8859-1") == "%A9" assert safe_url_string("http://www.example.org/") == "http://www.example.org/" alessi = "/ecommerce/oggetto/Te \xf2/tea-strainer/1273" assert ( safe_url_string(alessi) == "/ecommerce/oggetto/Te%20%C3%B2/tea-strainer/1273" ) assert ( safe_url_string( "http://www.example.com/test?p(29)url(http://www.another.net/page)" ) == "http://www.example.com/test?p(29)url(http://www.another.net/page)" ) assert ( safe_url_string( "http://www.example.com/Brochures_&_Paint_Cards&PageSize=200" ) == "http://www.example.com/Brochures_&_Paint_Cards&PageSize=200" ) # page-encoding does not affect URL path # we still end up UTF-8 encoding characters before percent-escaping safeurl = safe_url_string("http://www.example.com/£") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3" safeurl = safe_url_string("http://www.example.com/£", encoding="utf-8") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3" safeurl = safe_url_string("http://www.example.com/£", encoding="latin-1") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3" safeurl = safe_url_string("http://www.example.com/£", path_encoding="latin-1") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%A3" assert isinstance(safe_url_string(b"http://example.com/"), str) def test_safe_url_string_remove_ascii_tab_and_newlines(self): assert ( safe_url_string("http://example.com/test\n.html") == "http://example.com/test.html" ) assert ( safe_url_string("http://example.com/test\t.html") == "http://example.com/test.html" ) assert ( safe_url_string("http://example.com/test\r.html") == "http://example.com/test.html" ) assert ( safe_url_string("http://example.com/test\r.html\n") == "http://example.com/test.html" ) assert ( safe_url_string("http://example.com/test\r\n.html\t") == "http://example.com/test.html" ) assert ( safe_url_string("http://example.com/test\a\n.html") == "http://example.com/test%07.html" ) def test_safe_url_string_quote_path(self): safeurl = safe_url_string('http://google.com/"hello"', quote_path=True) assert safeurl == "http://google.com/%22hello%22" safeurl = safe_url_string('http://google.com/"hello"', quote_path=False) assert safeurl == 'http://google.com/"hello"' safeurl = safe_url_string('http://google.com/"hello"') assert safeurl == "http://google.com/%22hello%22" def test_safe_url_string_with_query(self): safeurl = safe_url_string("http://www.example.com/£?unit=µ") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%C2%B5" safeurl = safe_url_string("http://www.example.com/£?unit=µ", encoding="utf-8") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%C2%B5" safeurl = safe_url_string("http://www.example.com/£?unit=µ", encoding="latin-1") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%B5" safeurl = safe_url_string( "http://www.example.com/£?unit=µ", path_encoding="latin-1" ) assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%A3?unit=%C2%B5" safeurl = safe_url_string( "http://www.example.com/£?unit=µ", encoding="latin-1", path_encoding="latin-1", ) assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%A3?unit=%B5" def test_safe_url_string_misc(self): # mixing Unicode and percent-escaped sequences safeurl = safe_url_string("http://www.example.com/£?unit=%C2%B5") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%C2%B5" safeurl = safe_url_string("http://www.example.com/%C2%A3?unit=µ") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%C2%B5" def test_safe_url_string_invalid_scheme(self): # A scheme must start with a letter (RFC 3986); a leading digit or # symbol, or an empty scheme, is not a scheme. In particular an empty # scheme must not promote the rest into a scheme-relative URL, which # would expose an attacker-controlled host. assert safe_url_string("://evil.com/path") == "://evil.com/path" assert safe_url_string("1x://evil.com/path") == "1x://evil.com/path" assert safe_url_string("+x://evil.com/path") == "+x://evil.com/path" def test_safe_url_string_unclosed_bracket(self): for url in ( "http://[::1", "http://[::1/p]", "http://[::1?q=[a]", "http://[::1#f]", ): with pytest.raises(ValueError, match="Invalid IPv6 URL"): safe_url_string(url) def test_safe_url_string_bytes_input(self): safeurl = safe_url_string(b"http://www.example.com/") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/" # bytes input is assumed to be UTF-8 safeurl = safe_url_string(b"http://www.example.com/\xc2\xb5") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%B5" # page-encoding encoded bytes still end up as UTF-8 sequences in path safeurl = safe_url_string(b"http://www.example.com/\xb5", encoding="latin1") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%B5" safeurl = safe_url_string( b"http://www.example.com/\xa3?unit=\xb5", encoding="latin1" ) assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%C2%A3?unit=%B5" def test_safe_url_string_bytes_input_nonutf8(self): # latin1 safeurl = safe_url_string(b"http://www.example.com/\xa3?unit=\xb5") assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/%A3?unit=%B5" # cp1251 # >>> 'Россия'.encode('cp1251') # '\xd0\xee\xf1\xf1\xe8\xff' safeurl = safe_url_string( b"http://www.example.com/country/\xd0\xee\xf1\xf1\xe8\xff" ) assert isinstance(safeurl, str) assert safeurl == "http://www.example.com/country/%D0%EE%F1%F1%E8%FF" def test_safe_url_idna(self): # adapted from: # https://ssl.icu-project.org/icu-bin/idnbrowser # http://unicode.org/faq/idn.html # + various others websites = ( ( "http://www.färgbolaget.nu/färgbolaget", "http://www.xn--frgbolaget-q5a.nu/f%C3%A4rgbolaget", ), ( "http://www.räksmörgås.se/?räksmörgås=yes", "http://www.xn--rksmrgs-5wao1o.se/?r%C3%A4ksm%C3%B6rg%C3%A5s=yes", ), ( "http://www.brændendekærlighed.com/brændende/kærlighed", "http://www.xn--brndendekrlighed-vobh.com/br%C3%A6ndende/k%C3%A6rlighed", ), ("http://www.예비교사.com", "http://www.xn--9d0bm53a3xbzui.com"), ("http://理容ナカムラ.com", "http://xn--lck1c3crb1723bpq4a.com"), ("http://あーるいん.com", "http://xn--l8je6s7a45b.com"), # --- real websites --- # in practice, this redirect (301) to http://www.buecher.de/?q=b%C3%BCcher ( "http://www.bücher.de/?q=bücher", "http://www.xn--bcher-kva.de/?q=b%C3%BCcher", ), # Japanese ( "http://はじめよう.みんな/?query=サ&maxResults=5", "http://xn--p8j9a0d9c9a.xn--q9jyb4c/?query=%E3%82%B5&maxResults=5", ), # Russian ("http://кто.рф/", "http://xn--j1ail.xn--p1ai/"), ( "http://кто.рф/index.php?domain=Что", "http://xn--j1ail.xn--p1ai/index.php?domain=%D0%A7%D1%82%D0%BE", ), # Korean ("http://내도메인.한국/", "http://xn--220b31d95hq8o.xn--3e0b707e/"), ( "http://맨체스터시티축구단.한국/", "http://xn--2e0b17htvgtvj9haj53ccob62ni8d.xn--3e0b707e/", ), # Arabic ("http://nic.شبكة", "http://nic.xn--ngbc5azd"), # Chinese ("https://www.贷款.在线", "https://www.xn--0kwr83e.xn--3ds443g"), ("https://www2.xn--0kwr83e.在线", "https://www2.xn--0kwr83e.xn--3ds443g"), ("https://www3.贷款.xn--3ds443g", "https://www3.xn--0kwr83e.xn--3ds443g"), ) for idn_input, safe_result in websites: safeurl = safe_url_string(idn_input) assert safeurl == safe_result # make sure the safe URL is unchanged when made safe a 2nd time for _, safe_result in websites: safeurl = safe_url_string(safe_result) assert safeurl == safe_result def test_safe_url_idna_encoding_failure(self): # missing DNS label assert ( safe_url_string("http://.éxamplé.com/résumé?q=résumé") == "http://.éxamplé.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) # DNS label too long assert ( safe_url_string(f"http://www.{'éxamplé' * 11}.com/résumé?q=résumé") == f"http://www.{'éxamplé' * 11}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) # the fallback works when a non-UTF-8 page encoding is given assert ( safe_url_string("http://.éxamplé.com/", encoding="latin1") == "http://.éxamplé.com/" ) assert ( safe_url_string("http://.éxamplé.com:80/?q=a", encoding="utf-16") == "http://.éxamplé.com:80/?%FF%FEq%00=%00a%00" ) def test_safe_url_port_number(self): assert ( safe_url_string("http://www.example.com:80/résumé?q=résumé") == "http://www.example.com:80/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) assert ( safe_url_string("http://www.example.com:/résumé?q=résumé") == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) def test_safe_url_string_preserve_nonfragment_hash(self): # don't decode `%23` to `#` assert ( safe_url_string("http://www.example.com/path/to/%23/foo/bar") == "http://www.example.com/path/to/%23/foo/bar" ) assert ( safe_url_string("http://www.example.com/path/to/%23/foo/bar#frag") == "http://www.example.com/path/to/%23/foo/bar#frag" ) assert ( safe_url_string( "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2Fpath%2Fto%2F%23%2Fbar%2Ffoo" ) == "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2Fpath%2Fto%2F%23%2Fbar%2Ffoo" ) assert ( safe_url_string( "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag" ) == "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag" ) def test_safe_url_string_encode_idna_domain_with_port(self): assert ( safe_url_string("http://新华网.中国:80") == "http://xn--xkrr14bows.xn--fiqs8s:80" ) def test_safe_url_string_encode_idna_domain_with_username_password_and_port_number( self, ): assert ( safe_url_string("ftp://admin:admin@新华网.中国:21") == "ftp://admin:admin@xn--xkrr14bows.xn--fiqs8s:21" ) assert ( safe_url_string("http://Åsa:abc123@➡.ws:81/admin") == "http://%C3%85sa:abc123@xn--hgi.ws:81/admin" ) assert ( safe_url_string("http://japão:não@️i❤️.ws:8000/") == "http://jap%C3%A3o:n%C3%A3o@xn--i-7iq.ws:8000/" ) def test_safe_url_string_encode_idna_domain_with_username_and_empty_password_and_port_number( self, ): assert ( safe_url_string("ftp://admin:@新华网.中国:21") == "ftp://admin:@xn--xkrr14bows.xn--fiqs8s:21" ) assert ( safe_url_string("ftp://admin@新华网.中国:21") == "ftp://admin@xn--xkrr14bows.xn--fiqs8s:21" ) def test_safe_url_string_userinfo_unsafe_chars( self, ): assert ( safe_url_string("ftp://admin:|%@example.com") == "ftp://admin:%7C%25@example.com" ) def test_safe_url_string_user_and_pass_percentage_encoded(self): assert ( safe_url_string("http://%25user:%25pass@host") == "http://%25user:%25pass@host" ) assert ( safe_url_string("http://%user:%pass@host") == "http://%25user:%25pass@host" ) assert ( safe_url_string("http://%26user:%26pass@host") == "http://&user:&pass@host" ) assert ( safe_url_string("http://%2525user:%2525pass@host") == "http://%2525user:%2525pass@host" ) assert ( safe_url_string("http://%2526user:%2526pass@host") == "http://%2526user:%2526pass@host" ) assert ( safe_url_string("http://%25%26user:%25%26pass@host") == "http://%25&user:%25&pass@host" ) def test_safe_download_url(self): assert safe_download_url("http://www.example.org") == "http://www.example.org/" assert ( safe_download_url("http://www.example.org/../") == "http://www.example.org/" ) assert ( safe_download_url("http://www.example.org/../../images/../image") == "http://www.example.org/image" ) assert ( safe_download_url("http://www.example.org/dir/") == "http://www.example.org/dir/" ) assert ( safe_download_url(b"http://www.example.org/dir/") == "http://www.example.org/dir/" ) # trailing slash handling assert ( safe_download_url("http://www.example.org/dir/?a=b") == "http://www.example.org/dir/?a=b" ) assert ( safe_download_url("http://www.example.org/dir?a=b/") == "http://www.example.org/dir?a=b/" ) # Encoding related tests assert ( safe_download_url( b"http://www.example.org?\xa3", encoding="latin-1", path_encoding="latin-1", ) == "http://www.example.org/?%A3" ) assert ( safe_download_url( b"http://www.example.org?\xc2\xa3", encoding="utf-8", path_encoding="utf-8", ) == "http://www.example.org/?%C2%A3" ) assert ( safe_download_url( b"http://www.example.org/\xc2\xa3?\xc2\xa3", encoding="utf-8", path_encoding="latin-1", ) == "http://www.example.org/%A3?%C2%A3" ) def test_safe_download_url_encoded_dot_segments(self): # "%2e", ".%2e", "%2e." and "%2e%2e" are the percent-encoded forms of # the single-dot and double-dot path segments of the URL living # standard, resolved by clients like "." and "..". assert ( safe_download_url("http://www.example.org/dir/%2e%2e/secret") == "http://www.example.org/secret" ) assert ( safe_download_url( "http://www.example.org/%2E%2E/%2E%2E/images/%2e%2e/image" ) == "http://www.example.org/image" ) assert ( safe_download_url("http://www.example.org/dir/.%2e/%2e./a/%2e/b") == "http://www.example.org/a/b" ) # Segments that merely contain "%2e" are not dot segments. assert ( safe_download_url("http://www.example.org/a%2eb/%2ec/") == "http://www.example.org/a%2eb/%2ec/" ) def test_is_url(self): assert is_url("http://www.example.org") assert is_url("https://www.example.org") assert is_url("file:///some/path") assert not is_url("foo://bar") assert not is_url("foo--bar") def test_add_http_if_no_scheme(self): assert add_http_if_no_scheme("www.example.com") == "http://www.example.com" assert add_http_if_no_scheme("//www.example.com") == "http://www.example.com" assert ( add_http_if_no_scheme("https://www.example.com") == "https://www.example.com" ) assert ( add_http_if_no_scheme("HTTPS://www.example.com") == "HTTPS://www.example.com" ) def test_url_query_parameter(self): assert url_query_parameter("product.html?id=200&foo=bar", "id") == "200" assert ( url_query_parameter("product.html?id=200&foo=bar", "notthere", "mydefault") == "mydefault" ) assert url_query_parameter("product.html?id=", "id") is None assert url_query_parameter("product.html?id=", "id", keep_blank_values=1) == "" # only the first one is returned assert url_query_parameter("product.html?id=200&id=201&id=202", "id") == "200" # query delimiter at index 1 of a short relative URL assert url_query_parameter("a?id=200", "id") == "200" assert ( url_query_parameter("product.html?id=200;foo=bar", "id", separator=";") == "200" ) # ASCII tab and newlines are removed, like urllib.parse does assert url_query_parameter("product.html?id=200\n", "id") == "200" assert url_query_parameter("product.html?id=2\t00", "id") == "200" @pytest.mark.parametrize( ("url", "expected"), [ (b"product.html?id=200", "200"), (b"product.html?id=", ""), (b"product.html?id=caf%C3%A9", "café"), ("product.html?id=café".encode(), "café"), (b"product.html?other=1&id=200", "200"), ], ) def test_url_query_parameter_bytes(self, url: bytes, expected: str) -> None: assert url_query_parameter(url, "id", keep_blank_values=True) == expected @pytest.mark.parametrize( "url", [ "product.html?id=b%a3", b"product.html?id=b%a3", ], ) def test_url_query_parameter_non_utf8_escape(self, url: str | bytes) -> None: # a percent-escape that is not valid UTF-8 decodes to U+FFFD, as with # urllib.parse.parse_qs(), instead of raising assert url_query_parameter(url, "id") == "b\ufffd" @pytest.mark.xfail def test_url_query_parameter_2(self): """ This problem was seen several times in the feeds. Sometime affiliate URLs contains nested encoded affiliate URL with direct URL as parameters. For example: aff_url1 = 'http://www.tkqlhce.com/click-2590032-10294381?url=http%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FArgosCreateReferral%3FstoreId%3D10001%26langId%3D-1%26referrer%3DCOJUN%26params%3Dadref%253DGarden+and+DIY-%3EGarden+furniture-%3EChildren%26%2339%3Bs+garden+furniture%26referredURL%3Dhttp%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FProductDisplay%253FstoreId%253D10001%2526catalogId%253D1500001501%2526productId%253D1500357023%2526langId%253D-1' the typical code to extract needed URL from it is: aff_url2 = url_query_parameter(aff_url1, 'url') after this aff2_url is: 'http://www.argos.co.uk/webapp/wcs/stores/servlet/ArgosCreateReferral?storeId=10001&langId=-1&referrer=COJUN¶ms=adref%3DGarden and DIY->Garden furniture->Children's gardenfurniture&referredURL=http://www.argos.co.uk/webapp/wcs/stores/servlet/ProductDisplay%3FstoreId%3D10001%26catalogId%3D1500001501%26productId%3D1500357023%26langId%3D-1' the direct URL extraction is url = url_query_parameter(aff_url2, 'referredURL') but this will not work, because aff_url2 contains ' (comma sign encoded in the feed) and the URL extraction will fail, current workaround was made in the spider, just a replace for ' to %27 """ # correct case aff_url1 = "http://www.anrdoezrs.net/click-2590032-10294381?url=http%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FArgosCreateReferral%3FstoreId%3D10001%26langId%3D-1%26referrer%3DCOJUN%26params%3Dadref%253DGarden+and+DIY-%3EGarden+furniture-%3EGarden+table+and+chair+sets%26referredURL%3Dhttp%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FProductDisplay%253FstoreId%253D10001%2526catalogId%253D1500001501%2526productId%253D1500357199%2526langId%253D-1" aff_url2 = url_query_parameter(aff_url1, "url") assert ( aff_url2 == "http://www.argos.co.uk/webapp/wcs/stores/servlet/ArgosCreateReferral?storeId=10001&langId=-1&referrer=COJUN¶ms=adref%3DGarden and DIY->Garden furniture->Garden table and chair sets&referredURL=http://www.argos.co.uk/webapp/wcs/stores/servlet/ProductDisplay%3FstoreId%3D10001%26catalogId%3D1500001501%26productId%3D1500357199%26langId%3D-1" ) assert aff_url2 is not None prod_url = url_query_parameter(aff_url2, "referredURL") assert ( prod_url == "http://www.argos.co.uk/webapp/wcs/stores/servlet/ProductDisplay?storeId=10001&catalogId=1500001501&productId=1500357199&langId=-1" ) # weird case aff_url1 = "http://www.tkqlhce.com/click-2590032-10294381?url=http%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FArgosCreateReferral%3FstoreId%3D10001%26langId%3D-1%26referrer%3DCOJUN%26params%3Dadref%253DGarden+and+DIY-%3EGarden+furniture-%3EChildren%26%2339%3Bs+garden+furniture%26referredURL%3Dhttp%3A%2F%2Fwww.argos.co.uk%2Fwebapp%2Fwcs%2Fstores%2Fservlet%2FProductDisplay%253FstoreId%253D10001%2526catalogId%253D1500001501%2526productId%253D1500357023%2526langId%253D-1" aff_url2 = url_query_parameter(aff_url1, "url") assert ( aff_url2 == "http://www.argos.co.uk/webapp/wcs/stores/servlet/ArgosCreateReferral?storeId=10001&langId=-1&referrer=COJUN¶ms=adref%3DGarden and DIY->Garden furniture->Children's garden furniture&referredURL=http://www.argos.co.uk/webapp/wcs/stores/servlet/ProductDisplay%3FstoreId%3D10001%26catalogId%3D1500001501%26productId%3D1500357023%26langId%3D-1" ) assert aff_url2 is not None prod_url = url_query_parameter(aff_url2, "referredURL") # fails, prod_url is None now assert ( prod_url == "http://www.argos.co.uk/webapp/wcs/stores/servlet/ProductDisplay?storeId=10001&catalogId=1500001501&productId=1500357023&langId=-1" ) def test_add_or_replace_parameter(self): url = "http://domain/test" assert add_or_replace_parameter(url, "arg", "v") == "http://domain/test?arg=v" url = "http://domain/test?arg1=v1&arg2=v2&arg3=v3" assert ( add_or_replace_parameter(url, "arg4", "v4") == "http://domain/test?arg1=v1&arg2=v2&arg3=v3&arg4=v4" ) assert ( add_or_replace_parameter(url, "arg3", "nv3") == "http://domain/test?arg1=v1&arg2=v2&arg3=nv3" ) assert ( add_or_replace_parameter( "http://domain/moreInfo.asp?prodID=", "prodID", "20" ) == "http://domain/moreInfo.asp?prodID=20" ) url = "http://rmc-offers.co.uk/productlist.asp?BCat=2%2C60&CatID=60" assert ( add_or_replace_parameter(url, "BCat", "newvalue") == "http://rmc-offers.co.uk/productlist.asp?BCat=newvalue&CatID=60" ) url = "http://rmc-offers.co.uk/productlist.asp?BCat=2,60&CatID=60" assert ( add_or_replace_parameter(url, "BCat", "newvalue") == "http://rmc-offers.co.uk/productlist.asp?BCat=newvalue&CatID=60" ) url = "http://rmc-offers.co.uk/productlist.asp?" assert ( add_or_replace_parameter(url, "BCat", "newvalue") == "http://rmc-offers.co.uk/productlist.asp?BCat=newvalue" ) url = "http://example.com/?version=1&pageurl=http%3A%2F%2Fwww.example.com%2Ftest%2F%23fragment%3Dy¶m2=value2" assert ( add_or_replace_parameter(url, "version", "2") == "http://example.com/?version=2&pageurl=http%3A%2F%2Fwww.example.com%2Ftest%2F%23fragment%3Dy¶m2=value2" ) assert ( add_or_replace_parameter(url, "pageurl", "test") == "http://example.com/?version=1&pageurl=test¶m2=value2" ) url = "http://domain/test?arg1=v1&arg2=v2&arg1=v3" assert ( add_or_replace_parameter(url, "arg4", "v4") == "http://domain/test?arg1=v1&arg2=v2&arg1=v3&arg4=v4" ) assert ( add_or_replace_parameter(url, "arg1", "v3") == "http://domain/test?arg1=v3&arg2=v2" ) # ASCII tab and newlines are removed, like urllib.parse does assert ( add_or_replace_parameter("http://example.com/?a=1\n", "b", "2") == "http://example.com/?a=1&b=2" ) @pytest.mark.xfail(reason="https://github.com/scrapy/w3lib/issues/164") def test_add_or_replace_parameter_fail(self): assert ( add_or_replace_parameter("http://domain/test?arg1=v1;arg2=v2", "arg1", "v3") == "http://domain/test?arg1=v3&arg2=v2" ) def test_add_or_replace_parameter_semicolon(self): url = "http://domain/test?arg1=v1;arg2=v2;arg3=v3" assert ( add_or_replace_parameter(url, "arg4", "v4", separator=";") == "http://domain/test?arg1=v1;arg2=v2;arg3=v3;arg4=v4" ) assert ( add_or_replace_parameter(url, "arg3", "nv3", separator=";") == "http://domain/test?arg1=v1;arg2=v2;arg3=nv3" ) def test_add_or_replace_parameters(self): url = "http://domain/test" assert ( add_or_replace_parameters(url, {"arg": "v"}) == "http://domain/test?arg=v" ) url = "http://domain/test?arg1=v1&arg2=v2&arg3=v3" assert ( add_or_replace_parameters(url, {"arg4": "v4"}) == "http://domain/test?arg1=v1&arg2=v2&arg3=v3&arg4=v4" ) assert ( add_or_replace_parameters(url, {"arg4": "v4", "arg3": "v3new"}) == "http://domain/test?arg1=v1&arg2=v2&arg3=v3new&arg4=v4" ) url = "http://domain/test?arg1=v1&arg2=v2&arg1=v3" assert ( add_or_replace_parameters(url, {"arg4": "v4"}) == "http://domain/test?arg1=v1&arg2=v2&arg1=v3&arg4=v4" ) assert ( add_or_replace_parameters(url, {"arg1": "v3"}) == "http://domain/test?arg1=v3&arg2=v2" ) def test_add_or_replace_parameters_does_not_change_input_param(self): url = "http://domain/test?arg=original" input_param = {"arg": "value"} add_or_replace_parameters(url, input_param) assert input_param == {"arg": "value"} def test_url_query_cleaner(self): assert url_query_cleaner("product.html?") == "product.html" assert url_query_cleaner(b"product.html?") == "product.html" assert url_query_cleaner("product.html?&") == "product.html" assert ( url_query_cleaner("product.html?id=200&foo=bar&name=wired", ["id"]) == "product.html?id=200" ) # bytes URLs are decoded assert ( url_query_cleaner(b"product.html?id=200&foo=bar&name=wired", ["id"]) == "product.html?id=200" ) assert ( url_query_cleaner("product.html?&id=200&&foo=bar&name=wired", ["id"]) == "product.html?id=200" ) assert ( url_query_cleaner("product.html?foo=bar&name=wired", ["id"]) == "product.html" ) assert ( url_query_cleaner("product.html?id=200&foo=bar&name=wired", ["id", "name"]) == "product.html?id=200&name=wired" ) assert ( url_query_cleaner("product.html?id&other=3&novalue=", ["id"]) == "product.html?id" ) # default is to remove duplicate keys assert ( url_query_cleaner("product.html?d=1&e=b&d=2&d=3&other=other", ["d"]) == "product.html?d=1" ) # unique=False disables duplicate keys filtering assert ( url_query_cleaner( "product.html?d=1&e=b&d=2&d=3&other=other", ["d"], unique=False ) == "product.html?d=1&d=2&d=3" ) assert ( url_query_cleaner( "product.html?id=200&foo=bar&name=wired#id20", ["id", "foo"] ) == "product.html?id=200&foo=bar" ) assert ( url_query_cleaner( "product.html?id=200&foo=bar&name=wired", ["id"], remove=True ) == "product.html?foo=bar&name=wired" ) assert ( url_query_cleaner( "product.html?id=2&foo=bar&name=wired", ["id", "foo"], remove=True ) == "product.html?name=wired" ) assert ( url_query_cleaner( "product.html?id=2&foo=bar&name=wired", ["id", "footo"], remove=True ) == "product.html?foo=bar&name=wired" ) assert url_query_cleaner("product.html", ["id"], remove=True) == "product.html" assert ( url_query_cleaner("product.html?&", ["id"], remove=True) == "product.html" ) assert ( url_query_cleaner("product.html?foo=bar&name=wired", "foo") == "product.html?foo=bar" ) assert ( url_query_cleaner("product.html?foo=bar&foobar=wired", "foobar") == "product.html?foobar=wired" ) def test_url_query_cleaner_keep_fragments(self): assert ( url_query_cleaner( "product.html?id=200&foo=bar&name=wired#foo", ["id"], keep_fragments=True, ) == "product.html?id=200#foo" ) assert ( url_query_cleaner( "product.html?id=200&foo=bar&name=wired", ["id"], keep_fragments=True ) == "product.html?id=200" ) # no stray "#" when there is no fragment assert ( url_query_cleaner("product.html", ["id"], keep_fragments=True) == "product.html" ) assert ( url_query_cleaner("product.html?", ["id"], keep_fragments=True) == "product.html" ) def test_path_to_file_uri(self): if os.name == "nt": assert ( path_to_file_uri(r"C:\windows\clock.avi") == "file:///C:/windows/clock.avi" ) else: assert path_to_file_uri("/some/path.txt") == "file:///some/path.txt" fn = "test.txt" x = path_to_file_uri(fn) assert x.startswith("file:///") assert file_uri_to_path(x).lower() == str(Path(fn).absolute()).lower() @pytest.mark.skipif(os.name != "nt", reason="Windows UNC paths") @pytest.mark.parametrize( ("path", "uri"), [ (r"\\server\share\file.txt", "file://server/share/file.txt"), ( r"\\server\shared folder\café #1.txt", "file://server/shared%20folder/caf%C3%A9%20%231.txt", ), ], ) def test_path_to_file_uri_unc(self, path, uri): assert path_to_file_uri(path) == uri assert path_to_file_uri(Path(path)) == uri assert file_uri_to_path(path_to_file_uri(path)) == path @pytest.mark.skipif(os.name != "nt", reason="Windows UNC paths") @pytest.mark.parametrize( ("uri", "path"), [ ("file://server/share/file.txt", r"\\server\share\file.txt"), ( "file://server/shared%20folder/caf%C3%A9%20%231.txt", r"\\server\shared folder\café #1.txt", ), ("//server/share/file.txt", r"\\server\share\file.txt"), ], ) def test_file_uri_to_path_unc(self, uri, path): assert file_uri_to_path(uri) == path @pytest.mark.parametrize("host", ["localhost", "LOCALHOST"]) def test_file_uri_to_path_localhost(self, host): assert file_uri_to_path(f"file://{host}/foo/bar") == f"{os.sep}foo{os.sep}bar" def test_file_uri_to_path(self): if os.name == "nt": assert ( file_uri_to_path("file:///C:/windows/clock.avi") == r"C:\windows\clock.avi" ) uri = "file:///C:/windows/clock.avi" uri2 = path_to_file_uri(file_uri_to_path(uri)) assert uri == uri2 assert file_uri_to_path("///path/to/test.txt") == r"\path\to\test.txt" assert ( file_uri_to_path("/path/to/test%20file.txt?bar=baz") == r"\path\to\test file.txt" ) assert file_uri_to_path("file:///C:/temp/50%25.txt") == r"C:\temp\50%.txt" else: assert file_uri_to_path("file:///path/to/test.txt") == "/path/to/test.txt" assert file_uri_to_path("/path/to/test.txt") == "/path/to/test.txt" uri = "file:///path/to/test.txt" uri2 = path_to_file_uri(file_uri_to_path(uri)) assert uri == uri2 assert ( file_uri_to_path("//localhost/path/to/test.txt") == "/path/to/test.txt" ) assert file_uri_to_path("///path/to/test.txt") == "/path/to/test.txt" assert ( file_uri_to_path("/path/to/test%20file.txt?bar=baz") == "/path/to/test file.txt" ) assert file_uri_to_path("file:///dir/50%25.txt") == "/dir/50%.txt" assert file_uri_to_path("file:///dir/%41bc") == "/dir/Abc" assert file_uri_to_path(path_to_file_uri("/dir/50%.txt")) == "/dir/50%.txt" assert file_uri_to_path("test.txt") == "test.txt" assert file_uri_to_path("") == "" assert file_uri_to_path("/") == os.sep assert file_uri_to_path("///") == os.sep assert file_uri_to_path("////") == os.sep * 2 assert file_uri_to_path("//localhost/foo/bar") == f"{os.sep}foo{os.sep}bar" assert file_uri_to_path("///foo/bar") == f"{os.sep}foo{os.sep}bar" assert file_uri_to_path("////foo/bar") == f"{os.sep * 2}foo{os.sep}bar" @pytest.mark.parametrize( ("uri", "path"), [ ("file:///C:/a", r"C:\a"), # a leading slash run is shortened twice: once for the URI # authority, once for the drive-less path ("file:///////a/b", r"\\a\b"), ], ) def test_file_uri_to_path_windows(self, monkeypatch, uri, path): monkeypatch.setattr("w3lib._url._IS_WINDOWS", True) assert file_uri_to_path(uri) == path def test_file_uri_to_path_windows_bad_drive(self, monkeypatch): monkeypatch.setattr("w3lib._url._IS_WINDOWS", True) with pytest.raises(OSError, match="Bad URL"): file_uri_to_path("file:///C:/a:b") def test_any_to_uri(self): if os.name == "nt": assert any_to_uri(r"C:\windows\clock.avi") == "file:///C:/windows/clock.avi" else: assert any_to_uri("/some/path.txt") == "file:///some/path.txt" assert any_to_uri("file:///some/path.txt") == "file:///some/path.txt" assert ( any_to_uri("http://www.example.com/some/path.txt") == "http://www.example.com/some/path.txt" ) class TestSafeDownloadUrlProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: safe_download_url(url) class TestAddHttpIfNoSchemeProperties: @given(st.text() | hyp_urls()) def test_no_exception(self, url: str) -> None: add_http_if_no_scheme(url) class TestIsUrlProperties: @given(st.text() | hyp_urls()) def test_no_exception(self, url: str) -> None: is_url(url) class TestUrlQueryParameterProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: url_query_parameter(url, "foo") class TestUrlQueryCleanerProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: url_query_cleaner(url) class TestAddOrReplaceParameterProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: add_or_replace_parameter(url, "foo", "bar") class TestAddOrReplaceParametersProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: add_or_replace_parameters(url, {"foo": "bar"}) class TestSafeUrlStringProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: safe_url_string(url) @given(hyp_urls()) def test_idempotent(self, url: str) -> None: try: once = safe_url_string(url) except ValueError: return assert safe_url_string(once) == once class TestParseUrlProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: parse_url(url) @given(hyp_urls()) def test_idempotent(self, url: str) -> None: try: once = parse_url(url) except ValueError: return assert parse_url(once) == once class TestCanonicalizeUrl: def test_canonicalize_url(self): # simplest case assert canonicalize_url("http://www.example.com/") == "http://www.example.com/" def test_return_str(self): assert isinstance(canonicalize_url("http://www.example.com"), str) assert isinstance(canonicalize_url(b"http://www.example.com"), str) def test_append_missing_path(self): assert canonicalize_url("http://www.example.com") == "http://www.example.com/" def test_typical_usage(self): assert ( canonicalize_url("http://www.example.com/do?a=1&b=2&c=3") == "http://www.example.com/do?a=1&b=2&c=3" ) assert ( canonicalize_url("http://www.example.com/do?c=1&b=2&a=3") == "http://www.example.com/do?a=3&b=2&c=1" ) assert ( canonicalize_url("http://www.example.com/do?&a=1") == "http://www.example.com/do?a=1" ) def test_typical_usage_semicolon(self): assert ( canonicalize_url( "http://www.example.com/do?c=1;b=2;a=3", query_separator=";" ) == "http://www.example.com/do?a=3;b=2;c=1" ) def test_port_number(self): assert ( canonicalize_url("http://www.example.com:8888/do?a=1&b=2&c=3") == "http://www.example.com:8888/do?a=1&b=2&c=3" ) # trailing empty ports are removed assert ( canonicalize_url("http://www.example.com:/do?a=1&b=2&c=3") == "http://www.example.com/do?a=1&b=2&c=3" ) def test_sorting(self): assert ( canonicalize_url("http://www.example.com/do?c=3&b=5&b=2&a=50") == "http://www.example.com/do?a=50&b=2&b=5&c=3" ) def test_keep_blank_values(self): assert ( canonicalize_url( "http://www.example.com/do?b=&a=2", keep_blank_values=False ) == "http://www.example.com/do?a=2" ) assert ( canonicalize_url("http://www.example.com/do?b=&a=2") == "http://www.example.com/do?a=2&b=" ) assert ( canonicalize_url( "http://www.example.com/do?b=&c&a=2", keep_blank_values=False ) == "http://www.example.com/do?a=2" ) assert ( canonicalize_url("http://www.example.com/do?b=&c&a=2") == "http://www.example.com/do?a=2&b=&c=" ) assert ( canonicalize_url("http://www.example.com/do?1750,4") == "http://www.example.com/do?1750%2C4=" ) def test_spaces(self): assert ( canonicalize_url("http://www.example.com/do?q=a space&a=1") == "http://www.example.com/do?a=1&q=a+space" ) assert ( canonicalize_url("http://www.example.com/do?q=a+space&a=1") == "http://www.example.com/do?a=1&q=a+space" ) assert ( canonicalize_url("http://www.example.com/do?q=a%20space&a=1") == "http://www.example.com/do?a=1&q=a+space" ) def test_canonicalize_url_unicode_path(self): assert ( canonicalize_url("http://www.example.com/résumé") == "http://www.example.com/r%C3%A9sum%C3%A9" ) def test_canonicalize_url_unicode_query_string(self): # default encoding for path and query is UTF-8 assert ( canonicalize_url("http://www.example.com/résumé?q=résumé") == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) # passed encoding will affect query string assert ( canonicalize_url( "http://www.example.com/résumé?q=résumé", encoding="latin1" ) == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%E9sum%E9" ) assert ( canonicalize_url( "http://www.example.com/résumé?country=Россия", encoding="cp1251" ) == "http://www.example.com/r%C3%A9sum%C3%A9?country=%D0%EE%F1%F1%E8%FF" ) def test_canonicalize_url_unicode_query_string_wrong_encoding(self): # trying to encode with wrong encoding # fallback to UTF-8 assert ( canonicalize_url( "http://www.example.com/résumé?currency=€", encoding="latin1" ) == "http://www.example.com/r%C3%A9sum%C3%A9?currency=%E2%82%AC" ) assert ( canonicalize_url( "http://www.example.com/résumé?country=Россия", encoding="latin1" ) == "http://www.example.com/r%C3%A9sum%C3%A9?country=%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F" ) @pytest.mark.parametrize( "url", [ pytest.param("http://exa\tmple.com/a\r\nb?q=a\tb", id="str"), pytest.param(b"http://exa\tmple.com/a\r\nb?q=a\tb", id="bytes"), ], ) def test_canonicalize_url_remove_ascii_tab_and_newlines(self, url): # ASCII tab and newline are removed from anywhere in the URL, matching # safe_url_string() and the WHATWG/urlsplit behavior. This must not # depend on whether the input is str or bytes: a tab in the host of a # bytes URL was previously left in place, so the canonical form kept a # host a browser would connect to differently. assert canonicalize_url(url) == "http://example.com/ab?q=ab" def test_normalize_percent_encoding_in_paths(self): assert ( canonicalize_url("http://www.example.com/r%c3%a9sum%c3%a9") == "http://www.example.com/r%C3%A9sum%C3%A9" ) # non-UTF8 encoded sequences: they should be kept untouched, only upper-cased # 'latin1'-encoded sequence in path assert ( canonicalize_url("http://www.example.com/a%a3do") == "http://www.example.com/a%A3do" ) # 'latin1'-encoded path, UTF-8 encoded query string assert ( canonicalize_url("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9") == "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9" ) # 'latin1'-encoded path and query string assert ( canonicalize_url("http://www.example.com/a%a3do?q=r%e9sum%e9") == "http://www.example.com/a%A3do?q=r%E9sum%E9" ) url = "https://example.com/a%23b%2cc#bash" canonical = canonicalize_url(url) # %23 is not accidentally interpreted as a URL fragment separator assert canonical == "https://example.com/a%23b,c" assert canonical == canonicalize_url(canonical) def test_normalize_percent_encoding_in_query_arguments(self): assert ( canonicalize_url("http://www.example.com/do?k=b%a3") == "http://www.example.com/do?k=b%A3" ) assert ( canonicalize_url("http://www.example.com/do?k=r%c3%a9sum%c3%a9") == "http://www.example.com/do?k=r%C3%A9sum%C3%A9" ) def test_non_ascii_percent_encoding_in_paths(self): assert ( canonicalize_url("http://www.example.com/a do?a=1") == "http://www.example.com/a%20do?a=1" ) assert ( canonicalize_url("http://www.example.com/a %20do?a=1") == "http://www.example.com/a%20%20do?a=1" ) assert ( canonicalize_url("http://www.example.com/a do£.html?a=1") == "http://www.example.com/a%20do%C2%A3.html?a=1" ) assert ( canonicalize_url(b"http://www.example.com/a do\xc2\xa3.html?a=1") == "http://www.example.com/a%20do%C2%A3.html?a=1" ) def test_non_ascii_percent_encoding_in_query_arguments(self): assert ( canonicalize_url("http://www.example.com/do?price=£500&a=5&z=3") == "http://www.example.com/do?a=5&price=%C2%A3500&z=3" ) assert ( canonicalize_url(b"http://www.example.com/do?price=\xc2\xa3500&a=5&z=3") == "http://www.example.com/do?a=5&price=%C2%A3500&z=3" ) assert ( canonicalize_url(b"http://www.example.com/do?price(\xc2\xa3)=500&a=1") == "http://www.example.com/do?a=1&price%28%C2%A3%29=500" ) def test_urls_with_auth_and_ports(self): assert ( canonicalize_url("http://user:pass@www.example.com:81/do?now=1") == "http://user:pass@www.example.com:81/do?now=1" ) def test_remove_fragments(self): assert ( canonicalize_url("http://user:pass@www.example.com/do?a=1#frag") == "http://user:pass@www.example.com/do?a=1" ) assert ( canonicalize_url( "http://user:pass@www.example.com/do?a=1#frag", keep_fragments=True ) == "http://user:pass@www.example.com/do?a=1#frag" ) def test_remove_fragments_ipv6_host(self): # The fragment delimiter must still be detected when the netloc is a # bracketed IPv6 literal and the URL also has a query string. assert canonicalize_url("http://[::1]/do?a=1#frag") == "http://[::1]/do?a=1" assert ( canonicalize_url("http://[::1]/do?a=1#frag", keep_fragments=True) == "http://[::1]/do?a=1#frag" ) def test_remove_fragments_relative_url(self): # The fragment/query delimiter must be detected even when it sits at # index 0 or 1 of a relative URL (no authority to skip over). assert canonicalize_url("a#frag") == "a" assert canonicalize_url("a#frag", keep_fragments=True) == "a#frag" assert canonicalize_url("a?b=1#frag") == "a?b=1" assert canonicalize_url("?b=1") == "/?b=1" def test_dont_convert_safe_characters(self): # dont convert safe characters to percent encoding representation assert ( canonicalize_url( "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html" ) == "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html" ) def test_safe_characters_unicode(self): # urllib.quote uses a mapping cache of encoded characters. when parsing # an already percent-encoded url, it will fail if that url was not # percent-encoded as utf-8, that's why canonicalize_url must always # convert the urls to string. the following test asserts that # functionality. assert ( canonicalize_url("http://www.example.com/caf%E9-con-leche.htm") == "http://www.example.com/caf%E9-con-leche.htm" ) def test_domains_are_case_insensitive(self): assert canonicalize_url("http://www.EXAMPLE.com/") == "http://www.example.com/" def test_userinfo_is_case_sensitive(self): assert ( canonicalize_url("sftp://UsEr:PaSsWoRd@www.EXAMPLE.com/") == "sftp://UsEr:PaSsWoRd@www.example.com/" ) def test_resolve_dot_segments(self): assert ( canonicalize_url("http://www.example.com/a/b/../../c") == "http://www.example.com/c" ) assert ( canonicalize_url("http://www.example.com/a/./b") == "http://www.example.com/a/b" ) # a trailing ".." leaves a directory reference, regardless of # whether it is followed by a literal trailing slash assert ( canonicalize_url("http://www.example.com/a/b/..") == "http://www.example.com/a/" ) assert ( canonicalize_url("http://www.example.com/a/b/../") == "http://www.example.com/a/" ) # dot segments beyond the root are dropped, not turned into "../" assert ( canonicalize_url("http://www.example.com/../a") == "http://www.example.com/a" ) # percent-encoded dots are decoded before dot segments are resolved assert ( canonicalize_url("http://www.example.com/%2E%2E/a") == "http://www.example.com/a" ) def test_resolve_dot_segments_preserves_empty_segments(self): # An empty path segment is significant (RFC 3986): "/a//b" identifies a # different resource than "/a/b", so resolving dot segments must not # collapse consecutive slashes. assert ( canonicalize_url("http://www.example.com/a//b") == "http://www.example.com/a//b" ) assert ( canonicalize_url("http://www.example.com/a///b") == "http://www.example.com/a///b" ) # trailing empty segments are preserved too assert ( canonicalize_url("http://www.example.com/a/b//") == "http://www.example.com/a/b//" ) # a ".." still removes a preceding empty segment assert ( canonicalize_url("http://www.example.com/a//../b") == "http://www.example.com/a/b" ) def test_remove_dot_segments_rfc_examples(self): # RFC 3986, section 5.2.4 on absolute paths (canonicalize_url resolves # dot segments only for a path that starts with "/"). assert _remove_dot_segments("/a/b/c/./../../g") == "/a/g" # a trailing "/." or "/.." leaves a directory reference assert _remove_dot_segments("/a/.") == "/a/" assert _remove_dot_segments("/a/..") == "/" # a "/.." with nothing above the root cannot pop past it assert _remove_dot_segments("/..") == "/" # empty segments are preserved assert _remove_dot_segments("/a//b") == "/a//b" def test_opaque_path_dot_segments_are_left_untouched(self): # A path that does not start with "/" is opaque (URL Standard); its # dot segments are not resolved, matching browsers. assert canonicalize_url("mailto:a/../b") == "mailto:a/../b" # a hierarchical path (starts with "/") is still resolved assert canonicalize_url("foo:/a/../b") == "foo:/b" def test_normalize_ipv6_host(self): assert canonicalize_url("http://[::0:1]/") == "http://[::1]/" assert ( canonicalize_url("http://[2001:0DB8:0000:0000:0000:0000:0000:0001]:8080/a") == "http://[2001:db8::1]:8080/a" ) assert ( canonicalize_url("http://user:pass@[::1]/a") == "http://user:pass@[::1]/a" ) def test_canonicalize_idns(self): assert ( canonicalize_url("http://www.bücher.de?q=bücher") == "http://www.xn--bcher-kva.de/?q=b%C3%BCcher" ) # Japanese (+ reordering query parameters) assert ( canonicalize_url("http://はじめよう.みんな/?query=サ&maxResults=5") == "http://xn--p8j9a0d9c9a.xn--q9jyb4c/?maxResults=5&query=%E3%82%B5" ) # non-ASCII domain with an explicit port: IDNA encoding must only # apply to the host, not swallow the port separator assert ( canonicalize_url("http://www.bücher.de:8080/?q=bücher") == "http://www.xn--bcher-kva.de:8080/?q=b%C3%BCcher" ) def test_canonicalize_idns_with_userinfo(self): # userinfo must survive with its "@" delimiter instead of being # folded into the IDNA host label assert ( canonicalize_url("http://user@例え.jp/path") == "http://user@xn--r8jz45g.jp/path" ) assert ( canonicalize_url("http://user:pass@例え.jp:8080/p") == "http://user:pass@xn--r8jz45g.jp:8080/p" ) def test_quoted_slash_and_question_sign(self): assert ( canonicalize_url("http://foo.com/AC%2FDC+rocks%3f/?yeah=1") == "http://foo.com/AC%2FDC+rocks%3F/?yeah=1" ) assert canonicalize_url("http://foo.com/AC%2FDC/") == "http://foo.com/AC%2FDC/" def test_quoted_percent_sign(self): # a quoted percent sign (%25) must stay encoded, not decode to a bare % assert ( canonicalize_url("http://foo.com/cmp/Supermercados-Dia%25") == "http://foo.com/cmp/Supermercados-Dia%25" ) assert ( canonicalize_url("http://foo.com/100%25/path") == "http://foo.com/100%25/path" ) # idempotency: second canonicalization must be stable url = "http://foo.com/cmp/Supermercados-Dia%25" assert canonicalize_url(canonicalize_url(url)) == canonicalize_url(url) # double-encoded percent must stay double-encoded assert canonicalize_url("http://foo.com/%2525") == "http://foo.com/%2525" def test_quoted_semicolon(self): # a quoted semicolon (%3B) must stay encoded assert canonicalize_url("http://foo.com/x%3B") == "http://foo.com/x%3B" assert canonicalize_url("http://foo.com/%3b") == "http://foo.com/%3B" # idempotency: second canonicalization must be stable for url in ( "http://foo.com/x%3B", "http://foo.com/%0A%3BpE%7C", ): once = canonicalize_url(url) assert canonicalize_url(once) == once # an unencoded semicolon still marks a params component assert canonicalize_url("http://foo.com/x;b") == "http://foo.com/x;b" # double-encoded semicolon must stay double-encoded assert canonicalize_url("http://foo.com/%253B") == "http://foo.com/%253B" def test_canonicalize_urlparsed(self): # canonicalize_url() can be passed an already urlparse'd URL assert ( canonicalize_url(urlparse("http://www.example.com/résumé?q=résumé")) == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) assert ( canonicalize_url(urlparse("http://www.example.com/caf%e9-con-leche.htm")) == "http://www.example.com/caf%E9-con-leche.htm" ) assert ( canonicalize_url( urlparse("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9") ) == "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9" ) def test_canonicalize_parse_url(self): # parse_url() wraps urlparse and is used in link extractors assert ( canonicalize_url(parse_url("http://www.example.com/résumé?q=résumé")) == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) assert ( canonicalize_url(parse_url("http://www.example.com/caf%e9-con-leche.htm")) == "http://www.example.com/caf%E9-con-leche.htm" ) assert ( canonicalize_url( parse_url("http://www.example.com/a%a3do?q=r%c3%a9sum%c3%a9") ) == "http://www.example.com/a%A3do?q=r%C3%A9sum%C3%A9" ) assert ( canonicalize_url( parse_url( b"http://www.example.com/r\xe9sum\xe9?q=r\xe9sum\xe9", encoding="latin1", ) ) == "http://www.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) assert ( canonicalize_url(parse_url("http://www.example.com/path;params?x=1#frag")) == "http://www.example.com/path;params?x=1" ) assert ( canonicalize_url(parse_url("http://www.example.com/a;b/c;params?x=1")) == "http://www.example.com/a;b/c;params?x=1" ) assert ( canonicalize_url(parse_url("http://www.example.com/a;b/c")) == "http://www.example.com/a;b/c" ) assert ( canonicalize_url(parse_url("http://www.example.com/abc/def?x=1")) == "http://www.example.com/abc/def?x=1" ) def test_parse_url_parse_result(self): # an already parsed url is returned as is parts = parse_url("http://www.example.com/path;params?x=1#frag") assert parse_url(parts) is parts @pytest.mark.parametrize( "url", [ "http://www.example.com/public;/../admin/secret", "http://www.example.com/dir;x/file", "http://www.example.com/a;b/c", "http://www.example.com/a;b/c;d", ], ) def test_parse_url_non_final_segment_semicolon(self, url): # a ";" outside the last path segment is not a params delimiter assert parse_url(url).path == urlparse(url).path assert parse_url(url).params == urlparse(url).params @pytest.mark.parametrize( "url", [ "http://exa\tmple.com/p", "http://exa\nmple.com/p", "http://exa\rmple.com/p", "https://good.com\t.evil.com/a\r\nb?q=a\tb#f\tr", "http://example.com:8\t0/", ], ) def test_parse_url_remove_ascii_tab_and_newlines(self, url): # urlsplit drops every ASCII tab and newline from the URL, so a tab in # the host cannot survive into parse_url()'s netloc and report a host a # browser would not connect to. assert parse_url(url).netloc == urlparse(url).netloc assert parse_url(url).hostname == urlparse(url).hostname assert "\t" not in parse_url(url).netloc def test_urlsplit_remove_ascii_tab_and_newlines_from_scheme(self): # the default-scheme argument gets the same tab/newline removal as the # URL itself, matching urllib.parse.urlsplit assert _urlsplit("//example.com/p", "ht\ttp").scheme == "http" assert _urlsplit("//example.com/p", "ht\ntt\rp").scheme == "htttp" def test_canonicalize_url_non_final_segment_semicolon(self): # the path after such a ";" still gets percent-encoding normalization assert ( canonicalize_url("http://www.example.com/dir;x/a%7Eb") == "http://www.example.com/dir;x/a~b" ) def test_canonicalize_url_idempotence(self): for url, enc in [ ("http://www.bücher.de/résumé?q=résumé", "utf8"), ("http://www.example.com/résumé?q=résumé", "latin1"), ("http://www.example.com/résumé?country=Россия", "cp1251"), ("http://はじめよう.みんな/?query=サ&maxResults=5", "iso2022jp"), ]: canonicalized = canonicalize_url(url, encoding=enc) # if we canonicalize again, we ge the same result assert canonicalize_url(canonicalized, encoding=enc) == canonicalized # without encoding, already canonicalized URL is canonicalized identically assert canonicalize_url(canonicalized) == canonicalized def test_canonicalize_url_idna_exceptions(self): # missing DNS label assert ( canonicalize_url("http://.éxamplé.com/résumé?q=résumé") == "http://.éxamplé.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) # DNS label too long assert ( canonicalize_url(f"http://www.{'éxamplé' * 11}.com/résumé?q=résumé") == f"http://www.{'éxamplé' * 11}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9" ) def test_preserve_nonfragment_hash(self): # don't decode `%23` to `#` assert ( canonicalize_url("http://www.example.com/path/to/%23/foo/bar") == "http://www.example.com/path/to/%23/foo/bar" ) assert ( canonicalize_url("http://www.example.com/path/to/%23/foo/bar#frag") == "http://www.example.com/path/to/%23/foo/bar" ) assert ( canonicalize_url( "http://www.example.com/path/to/%23/foo/bar#frag", keep_fragments=True ) == "http://www.example.com/path/to/%23/foo/bar#frag" ) assert ( canonicalize_url( "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2Fpath%2Fto%2F%23%2Fbar%2Ffoo" ) == "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2Fpath%2Fto%2F%23%2Fbar%2Ffoo" ) assert ( canonicalize_url( "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag" ) == "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo" ) assert ( canonicalize_url( "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag", keep_fragments=True, ) == "http://www.example.com/path/to/%23/foo/bar?url=http%3A%2F%2Fwww.example.com%2F%2Fpath%2Fto%2F%23%2Fbar%2Ffoo#frag" ) def test_strip_spaces(self): assert canonicalize_url(" https://example.com") == "https://example.com/" assert canonicalize_url("https://example.com ") == "https://example.com/" assert canonicalize_url(" https://example.com ") == "https://example.com/" def test_unclosed_bracket(self): for url in ( "http://[::1", "http://[::1/p]", "http://[::1?q=[a]", "http://[::1#f]", ): with pytest.raises(ValueError, match="Invalid IPv6 URL"): canonicalize_url(url) class TestCanonicalizeUrlProperties: @given(hyp_urls()) def test_no_exception(self, url: str) -> None: canonicalize_url(url) @given(hyp_urls()) def test_idempotent(self, url: str) -> None: try: once = canonicalize_url(url) except ValueError: return assert canonicalize_url(once) == once class TestDataURI: def test_default_mediatype_charset(self): result = parse_data_uri("data:,A%20brief%20note") assert result.media_type == "text/plain" assert result.media_type_parameters == {"charset": "US-ASCII"} assert result.data == b"A brief note" def test_text_uri(self): result = parse_data_uri("data:,A%20brief%20note") assert result.data == b"A brief note" def test_bytes_uri(self): result = parse_data_uri(b"data:,A%20brief%20note") assert result.data == b"A brief note" def test_unicode_uri(self): result = parse_data_uri("data:,é") assert result.data == "é".encode() def test_default_mediatype(self): result = parse_data_uri("data:;charset=iso-8859-7,%be%d3%be") assert result.media_type == "text/plain" assert result.media_type_parameters == {"charset": "iso-8859-7"} assert result.data == b"\xbe\xd3\xbe" def test_text_charset(self): result = parse_data_uri("data:text/plain;charset=iso-8859-7,%be%d3%be") assert result.media_type == "text/plain" assert result.media_type_parameters == {"charset": "iso-8859-7"} assert result.data == b"\xbe\xd3\xbe" def test_mediatype_parameters(self): result = parse_data_uri( "data:text/plain;" "foo=%22foo;bar%5C%22%22;" "charset=utf-8;" "bar=%22foo;%5C%22foo%20;/%20,%22," "%CE%8E%CE%A3%CE%8E" ) assert result.media_type == "text/plain" assert result.media_type_parameters == { "charset": "utf-8", "foo": 'foo;bar"', "bar": 'foo;"foo ;/ ,', } assert result.data == b"\xce\x8e\xce\xa3\xce\x8e" def test_mediatype_parameter_empty_quoted_value(self): result = parse_data_uri('data:text/plain;foo="",AAA') assert result.media_type == "text/plain" assert result.media_type_parameters == {"foo": ""} assert result.data == b"AAA" def test_base64(self): result = parse_data_uri("data:text/plain;base64,SGVsbG8sIHdvcmxkLg%3D%3D") assert result.media_type == "text/plain" assert result.data == b"Hello, world." def test_base64_spaces(self): result = parse_data_uri( "data:text/plain;base64,SGVsb%20G8sIH%0A%20%20dvcm%20%20%20xk%20Lg%3D%0A%3D" ) assert result.media_type == "text/plain" assert result.data == b"Hello, world." result = parse_data_uri( "data:text/plain;base64,SGVsb G8sIH\n dvcm xk Lg%3D\n%3D" ) assert result.media_type == "text/plain" assert result.data == b"Hello, world." def test_wrong_base64_param(self): with pytest.raises(ValueError, match="invalid data URI"): parse_data_uri("data:text/plain;baes64,SGVsbG8sIHdvcmxkLg%3D%3D") def test_missing_comma(self): with pytest.raises(ValueError, match="invalid data URI"): parse_data_uri("data:A%20brief%20note") def test_missing_scheme(self): with pytest.raises(ValueError, match="invalid URI"): parse_data_uri("text/plain,A%20brief%20note") def test_wrong_scheme(self): with pytest.raises(ValueError, match="not a data URI"): parse_data_uri("http://example.com/") def test_data_prefixed_scheme(self): for uri in ("datax:,A%20brief%20note", "database:,A%20brief%20note"): with pytest.raises(ValueError, match="not a data URI"): parse_data_uri(uri) def test_scheme_case_insensitive(self): result = parse_data_uri("DATA:,A%20brief%20note") assert result.data == b"A brief note" result = parse_data_uri("DaTa:,A%20brief%20note") assert result.data == b"A brief note" class TestParseQsl: """Cases are copied from https://github.com/python/cpython/blob/main/Lib/test/test_urlparse.py""" @pytest.mark.parametrize( ("qs", "output"), [ ("", []), ("&", []), ("&&", []), ("=", [(b"", b"")]), ("=a", [(b"", b"a")]), ("a", [(b"a", b"")]), ("a=", [(b"a", b"")]), ("&a=b", [(b"a", b"b")]), ("a=a+b&b=b+c", [(b"a", b"a b"), (b"b", b"b c")]), ("a=1&a=2", [(b"a", b"1"), (b"a", b"2")]), (b"", []), (b"&", []), (b"&&", []), (b"=", [(b"", b"")]), (b"=a", [(b"", b"a")]), (b"a", [(b"a", b"")]), (b"a=", [(b"a", b"")]), (b"&a=b", [(b"a", b"b")]), (b"a=a+b&b=b+c", [(b"a", b"a b"), (b"b", b"b c")]), (b"a=1&a=2", [(b"a", b"1"), (b"a", b"2")]), (";a=b", [(b";a", b"b")]), ("a=a+b;b=b+c", [(b"a", b"a b;b=b c")]), (b";a=b", [(b";a", b"b")]), (b"a=a+b;b=b+c", [(b"a", b"a b;b=b c")]), ("\u0141=\xe9", [(b"\xc5\x81", b"\xc3\xa9")]), ("%C5%81=%C3%A9", [(b"\xc5\x81", b"\xc3\xa9")]), ("%81=%A9", [(b"\x81", b"\xa9")]), (b"\xc5\x81=\xc3\xa9", [(b"\xc5\x81", b"\xc3\xa9")]), (b"%C5%81=%C3%A9", [(b"\xc5\x81", b"\xc3\xa9")]), (b"\x81=\xa9", [(b"\x81", b"\xa9")]), (b"%81=%A9", [(b"\x81", b"\xa9")]), ("%41%42%43=%61%62%63", [(b"ABC", b"abc")]), ("%2D%2E%5F%7E=%30%39", [(b"-._~", b"09")]), (b"%41%42%43=%61%62%63", [(b"ABC", b"abc")]), (b"%2D%2E%5F%7E=%30%39", [(b"-._~", b"09")]), ], ) def test_parse_qsl(self, qs, output): assert parse_qsl_to_bytes(qs, keep_blank_values=True) == output output_without_blanks = [v for v in output if len(v[1])] assert parse_qsl_to_bytes(qs, keep_blank_values=False) == output_without_blanks class TestPrivateHelpers: @pytest.mark.parametrize( ("url", "expected"), [ ("http://example.com/path", ("http", "example.com", "/path", "", "")), ( "http://example.com/path?query", ("http", "example.com", "/path", "query", ""), ), ( "http://example.com/path#fragment", ("http", "example.com", "/path", "", "fragment"), ), ( "http://example.com/path?query#fragment", ("http", "example.com", "/path", "query", "fragment"), ), ( "a,b://example.com/path?query#fragment", ("", "", "a,b://example.com/path", "query", "fragment"), ), ], ) def test_urlsplit(self, url: str, expected: tuple[str, str, str, str, str]) -> None: assert tuple(_urlsplit(url)) == expected @pytest.mark.parametrize( ("components", "expected"), [ (("http", "example.com", "path", "", ""), "http://example.com/path"), (("http", "example.com", "/path", "", ""), "http://example.com/path"), (("http", "", "path", "", ""), "http:path"), (("http", "", "/path", "", ""), "http:///path"), (("mailto", "", "user@example.com", "", ""), "mailto:user@example.com"), (("", "", "//foo", "", ""), "////foo"), (("", "", "", "q", ""), "?q"), (("", "", "", "", "frag"), "#frag"), (("", "", "", "q", "frag"), "?q#frag"), (("http", "example.com", "", "q", "frag"), "http://example.com?q#frag"), ], ) def test_urlunsplit(self, components, expected): assert _urlunsplit(*components) == expected @pytest.mark.parametrize( ("components", "expected"), [ (("http", "example.com", "path", "", "", ""), "http://example.com/path"), ( ("http", "example.com", "/path", "a=1", "b=2", "frag"), "http://example.com/path;a=1?b=2#frag", ), (("http", "", "path", "", "", ""), "http:path"), (("http", "", "/path", "", "q=1", "frag"), "http:///path?q=1#frag"), (("mailto", "", "user@example.com", "", "", ""), "mailto:user@example.com"), ], ) def test_urlunparse(self, components, expected): assert _urlunparse(*components) == expected @pytest.mark.parametrize( ("path", "expected"), [ # a ";" in the last segment starts the params ("/a;b", ("/a", "b")), ("/a/b;c", ("/a/b", "c")), ("/a;b/c;d", ("/a;b/c", "d")), ("/a;b/c;", ("/a;b/c", "")), # a ";" in an earlier segment is an ordinary path character ("/a;b/c", ("/a;b/c", "")), ("/dir;x/file", ("/dir;x/file", "")), ("/public;/../admin/secret", ("/public;/../admin/secret", "")), # without a "/" the first ";" starts the params ("a;b", ("a", "b")), (";a", ("", "a")), # no ";" at all ("/a/b", ("/a/b", "")), ("", ("", "")), ], ) def test_split_params(self, path, expected): assert _split_params("http", path) == expected # schemes that do not use params keep the path intact assert _split_params("data", path) == (path, "") @pytest.mark.parametrize( ("netloc", "expected"), [ # no brackets at all ("example.com", "example.com"), # unclosed bracket ("[::1", "[::1"), # content between brackets is not a valid IP address ("[not-an-address]", "[not-an-address]"), # an IPv4 address in brackets is left untouched ("[127.0.0.1]", "[127.0.0.1]"), # a valid IPv6 address is normalized ("[::0:1]", "[::1]"), ], ) def test_normalize_ipv6_host(self, netloc, expected): assert _normalize_ipv6_host(netloc) == expected class TestPrivateHelpersProperties: @example("/") @given(st.text()) def test_quote_matches_stdlib(self, data: str) -> None: result = _quote(data.encode("utf-8"), safe=b"/").decode("utf-8") expected = quote(data) assert result == expected @given(st.text()) def test_quote_plus_matches_stdlib(self, data: str) -> None: result = _quote(data.encode("utf-8"), quote_plus=True).decode("utf-8") expected = quote_plus(data) assert result == expected @given(st.text()) def test_unquote_matches_stdlib(self, data: str) -> None: result = _unquote(data) expected = unquote_to_bytes(data) assert result == expected @given(st.text()) def test_unquote_plus_matches_stdlib(self, data: str) -> None: result = _unquote_plus(data) expected = unquote_to_bytes(data.replace("+", " ")) assert result == expected # assume() rejects most generated inputs on Python 3.10, tripping the check @settings(suppress_health_check=[HealthCheck.filter_too_much]) @given(st.text()) def test_parse_qs_matches_stdlib(self, data: str) -> None: if sys.version_info < (3, 11): # https://github.com/python/cpython/issues/74668 assume(data.isascii()) result = _parse_qs(data) expected = parse_qs(data.encode("utf-8")) assert result == expected @settings(suppress_health_check=[HealthCheck.filter_too_much]) @given(st.text()) def test_parse_qsl_matches_stdlib(self, data: str) -> None: if sys.version_info < (3, 11): assume(data.isascii()) result = _parse_qsl(data) expected = parse_qsl(data.encode("utf-8")) assert result == expected @given(hyp_urls()) def test_urlparse_matches_stdlib(self, url: str) -> None: result = _urlparse(url) expected = urlparse(url) assert result.scheme == expected.scheme assert result.netloc == expected.netloc assert result.path == expected.path assert result.query == expected.query assert result.fragment == expected.fragment @given(hyp_urls()) def test_urlsplit_matches_stdlib(self, url: str) -> None: result = _urlsplit(url) expected = urlsplit(url) assert result.scheme == expected.scheme assert result.netloc == expected.netloc assert result.path == expected.path assert result.query == expected.query assert result.fragment == expected.fragment @given(st.text() | hyp_urls()) def test_urlunparse_matches_stdlib(self, url: str) -> None: parsed = urlparse(url) result = _urlunparse(*parsed) expected = urlunparse(parsed) assert result == expected @given(st.text() | hyp_urls()) def test_urlunsplit_matches_stdlib(self, url: str) -> None: split = urlsplit(url) result = _urlunsplit(*split) expected = urlunsplit(split) assert result == expected scrapy-w3lib-d6b4a87/tests/test_util.py000066400000000000000000000064551525715767700202420ustar00rootroot00000000000000import pytest from w3lib._util import iter_tag_attributes, to_unicode with pytest.warns(DeprecationWarning, match="The w3lib.util module is deprecated."): from w3lib.util import to_bytes class TestToBytesDeprecated: def test_type_error(self): with pytest.raises(TypeError): to_bytes(True) # type: ignore[arg-type] def test_bytes_passthrough(self): data = b"caf\xe9" assert to_bytes(data) is data def test_str(self): assert to_bytes("café") == b"caf\xc3\xa9" def test_encoding(self): assert to_bytes("café", encoding="latin1") == b"caf\xe9" def test_errors(self): with pytest.raises(UnicodeEncodeError): to_bytes("café", encoding="ascii") assert to_bytes("café", encoding="ascii", errors="replace") == b"caf?" class TestToUnicode: def test_type_error(self): with pytest.raises(TypeError): to_unicode(True) # type: ignore[arg-type] def test_str_passthrough(self): data = "café" assert to_unicode(data) is data def test_bytes(self): assert to_unicode(b"caf\xc3\xa9") == "café" def test_encoding(self): assert to_unicode(b"caf\xe9", encoding="latin1") == "café" def test_errors(self): with pytest.raises(UnicodeDecodeError): to_unicode(b"caf\xe9") assert to_unicode(b"caf\xe9", errors="replace") == "caf\ufffd" class TestIterTagAttributes: @pytest.mark.parametrize( ("attrs", "expected"), [ ("", []), (" ", []), ("a=1 b=2", [("a", "1"), ("b", "2")]), ("a=\"1\" b='2' c=3", [("a", "1"), ("b", "2"), ("c", "3")]), # whitespace around the equals sign, and inside quoted values ('a = 1 b\t=\n"x y"', [("a", "1"), ("b", "x y")]), # names are lowercased, values are not ("HTTP-Equiv=Refresh", [("http-equiv", "Refresh")]), # valueless attributes are skipped, and so are stray characters ("a b=1 c / = d=2", [("b", "1"), ("d", "2")]), ("/ a=1 />", [("a", "1")]), # an empty value is still a value ("a=\"\" b='' c=", [("a", ""), ("b", ""), ("c", "")]), # whitespace after the equals sign is skipped, as in HTML ("a= b c=1", [("a", "b"), ("c", "1")]), # quotes that do not open a quoted value are ordinary characters ('a=b"c" d=\'e', [("a", "b"), ("d", "")]), # an unquoted value ends at whitespace or at a closing bracket ("a=1>b=2 c=3;x=4", [("a", "1"), ("b", "2"), ("c", "3;x=4")]), # a quoted value may contain what looks like other attributes ('a="b=1 c=2" d=3', [("a", "b=1 c=2"), ("d", "3")]), # repeated attributes are all yielded, in order ("a=1 a=2", [("a", "1"), ("a", "2")]), ], ) def test_all(self, attrs, expected): assert list(iter_tag_attributes(attrs)) == expected def test_linear_on_crafted_input(self): # 100k attributes, both wanted and not, must not take super-linear time attrs = "http-equiv refresh " * 50000 + 'content="3; url=/next"' assert list(iter_tag_attributes(attrs)) == [("content", "3; url=/next")] assert len(list(iter_tag_attributes("a=1 " * 100000))) == 100000 scrapy-w3lib-d6b4a87/tox.ini000066400000000000000000000026751525715767700160250ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py{310-315}, pypy3.11, docs, pylint, typing, pre-commit, twinecheck, benchmark [testenv] deps = hypothesis >= 6.148.0 pytest !=3.1.1, !=3.1.2 pytest-cov >= 7.0.0 pytest-xdist commands = python -m pytest \ --doctest-modules \ --cov=w3lib --cov-report=term --cov-report=xml -n auto \ {posargs:w3lib tests} [testenv:typing] basepython = python3 deps = pytest==9.1.1 mypy==2.3.0 hypothesis==6.165.7 commands = mypy {posargs: w3lib tests} [testenv:pylint] deps = {[testenv]deps} pylint==4.0.5 commands = pylint docs tests w3lib [testenv:docs] changedir = docs deps = -rdocs/requirements.txt commands = sphinx-build -W -b html . {envtmpdir}/html [testenv:pre-commit] deps = pre-commit commands = pre-commit run --all-files --show-diff-on-failure skip_install = true [testenv:twinecheck] basepython = python3 deps = twine==7.0.0 build==1.5.0 commands = python -m build --sdist twine check dist/* [testenv:benchmark] basepython = python3.13 deps = {[testenv]deps} pytest-codspeed passenv = *codspeed* *ci* commands = python -m pytest tests/benchmarks/ --no-cov --codspeed --codspeed-mode=simulation scrapy-w3lib-d6b4a87/w3lib/000077500000000000000000000000001525715767700155205ustar00rootroot00000000000000scrapy-w3lib-d6b4a87/w3lib/__init__.py000066400000000000000000000001511525715767700176260ustar00rootroot00000000000000__version__ = "2.5.0" version_info = tuple(int(v) if v.isdigit() else v for v in __version__.split(".")) scrapy-w3lib-d6b4a87/w3lib/_infra.py000066400000000000000000000007251525715767700173340ustar00rootroot00000000000000# https://infra.spec.whatwg.org/ import string # https://infra.spec.whatwg.org/commit-snapshots/59e0d16c1e3ba0e77c6a60bfc69a0929b8ffaa5d/#code-points _ASCII_TAB_OR_NEWLINE = "\t\n\r" _ASCII_WHITESPACE = "\t\n\x0c\r " _C0_CONTROL = "".join(chr(n) for n in range(32)) _C0_CONTROL_OR_SPACE = _C0_CONTROL + " " _ASCII_DIGIT = string.digits _ASCII_HEX_DIGIT = string.hexdigits _ASCII_ALPHA = string.ascii_letters _ASCII_ALPHANUMERIC = string.ascii_letters + string.digits scrapy-w3lib-d6b4a87/w3lib/_types.py000066400000000000000000000003161525715767700173750ustar00rootroot00000000000000from __future__ import annotations from typing import TypeAlias # the base class UnicodeError doesn't have attributes like start / end AnyUnicodeError: TypeAlias = UnicodeEncodeError | UnicodeDecodeError scrapy-w3lib-d6b4a87/w3lib/_url.py000066400000000000000000000600371525715767700170410ustar00rootroot00000000000000from __future__ import annotations import dataclasses import functools import ipaddress import os import re import string import sys import unicodedata from typing import TYPE_CHECKING from urllib.parse import ParseResult, scheme_chars, uses_netloc, uses_params from w3lib._infra import _ASCII_TAB_OR_NEWLINE, _C0_CONTROL_OR_SPACE if TYPE_CHECKING: from collections.abc import Generator from urllib.parse import _QueryType _IS_WINDOWS = os.name == "nt" _FS_ENCODING = sys.getfilesystemencoding() _FS_ERRORS = sys.getfilesystemencodeerrors() # https://url.spec.whatwg.org/ # https://url.spec.whatwg.org/commit-snapshots/a46cb9188a48c2c9d80ba32a9b1891652d6b4900/#default-port _DEFAULT_PORTS = { "ftp": 21, "file": None, "http": 80, "https": 443, "ws": 80, "wss": 443, } _SPECIAL_SCHEMES = set(_DEFAULT_PORTS.keys()) # constants from RFC 3986, Section 2.2 and 2.3 RFC3986_GEN_DELIMS = b":/?#[]@" RFC3986_SUB_DELIMS = b"!$&'()*+,;=" RFC3986_RESERVED = RFC3986_GEN_DELIMS + RFC3986_SUB_DELIMS RFC3986_UNRESERVED = (string.ascii_letters + string.digits + "-._~").encode("ascii") EXTRA_SAFE_CHARS = b"|" # see https://github.com/scrapy/w3lib/pull/25 RFC3986_USERINFO_SAFE_CHARS = RFC3986_UNRESERVED + RFC3986_SUB_DELIMS + b":" _SAFE_CHARS = RFC3986_RESERVED + RFC3986_UNRESERVED + EXTRA_SAFE_CHARS + b"%" _PATH_SAFE_CHARS = _SAFE_CHARS.replace(b"#", b"") _PATH_SAFE_CHARS_STR = _PATH_SAFE_CHARS.decode() _USES_NETLOC = frozenset(uses_netloc) _SCHEME_CHARS = frozenset(scheme_chars) _USES_PARAMS = frozenset(uses_params) _ASCII_TAB_OR_NEWLINE_TRANSLATION_TABLE = str.maketrans("", "", _ASCII_TAB_OR_NEWLINE) _C0_CONTROL_OR_SPACE_RE = re.compile(rf"[{_C0_CONTROL_OR_SPACE}]") _SCHEME_RE = re.compile(rf"^([a-zA-Z][{re.escape(scheme_chars)}]*):") _IPV_FUTURE_RE = re.compile(r"\Av[a-fA-F0-9]+\..+\Z") # "\" terminates the authority of a special-scheme URL just like "/" under the # URL living standard, so it belongs with the other authority delimiters here. _NETLOC_DELIMS_RE = re.compile(r"[/?#@:\\]") _NETLOC_STRIP_CHARS = str.maketrans("", "", "@:#?") def _strip(input_string: str) -> str: if not input_string: return input_string if not _C0_CONTROL_OR_SPACE_RE.search(input_string): return input_string return input_string.strip(_C0_CONTROL_OR_SPACE).translate( _ASCII_TAB_OR_NEWLINE_TRANSLATION_TABLE ) @functools.cache def _hex_encode_table() -> bytes: """Build a lookup table for percent-encoded byte values. | byte | encoding | |------|----------| | 0 | %00 | | 1 | %01 | | ... | ... | | 255 | %FF | Each entry is exactly 3 bytes: b"%HH". Returns: A bytes object of length 256 * 3 containing all percent encodings. """ return b"".join(f"%{i:02X}".encode() for i in range(256)) @functools.cache def _hex_decode_table() -> bytes: """Build a lookup table for decoding hex ASCII characters. | ASCII | value | |--------|--------------| | '0'-'9'| 0-9 | | 'A'-'F'| 10-15 | | 'a'-'f'| 10-15 | | other | 255 (invalid)| Returns: A bytes object of length 256 containing nibble values. """ table = bytearray([255]) * 256 table[48:58] = bytes(range(10)) # '0'-'9' table[65:71] = bytes(range(10, 16)) # 'A'-'F' table[97:103] = bytes(range(10, 16)) # 'a'-'f' return bytes(table) @functools.cache def _safe_table(safe: bytes = RFC3986_UNRESERVED) -> bytes: """Build a lookup table marking safe (non-encoded) bytes. | byte | is allowed? | |------|-------------| | 0 | 0 | | 32 | 1 (if safe) | | 65 | 1 | | 255 | 0 | Returns: A bytes object of length 256 acting as a boolean mask (0/1). """ table = bytearray(256) for b in safe: table[b] = 1 return bytes(table) @functools.cache def _quote_table(safe: bytes = b"", quote_plus: bool = False) -> tuple[bytes, ...]: """Precompute encoding rules for all 256 byte values. Decision table: | condition | output | |-------------------------------|--------| | byte in safe | as-is | | byte == 32 and quote_plus | "+" | | otherwise | "%HH" | Example mapping: | byte | char | output | |------|------|--------| | 65 | A | b"A" | | 32 | space| b"+" | | 255 | N/A | b"%FF" | Returns: A 256-entry tuple mapping byte value (index) -> encoded bytes. """ hex_table = _hex_encode_table() allowed = _safe_table(RFC3986_UNRESERVED + safe) if safe else _safe_table() output: list[bytes] = [b""] * 256 for idx, byte in enumerate(range(256)): if allowed[byte]: output[idx] = chr(byte).encode() elif quote_plus and byte == 32: # ord(' ') output[idx] = b"+" else: offset = byte * 3 output[idx] = hex_table[offset : offset + 3] return tuple(output) def _quote(data: bytes, safe: bytes = b"", quote_plus: bool = False) -> bytes: """Fast URL-style quoting using a precomputed table. Args: data: Input bytes. safe: Additional unescaped bytes. quote_plus: Encode space as '+' if True. Returns: Percent-encoded bytes. """ if not data: # pragma: no cover return b"" transform_table = _quote_table(safe, quote_plus) return b"".join([transform_table[byte] for byte in data]) def _quote_into( data: bytes, output: bytearray, safe: bytes = b"", quote_plus: bool = False ) -> None: if not data: # pragma: no cover return transform_table = _quote_table(safe, quote_plus) output += b"".join([transform_table[byte] for byte in data]) def _unquote(data: bytes | bytearray | str) -> bytes: if not data: return b"" if isinstance(data, str): data = data.encode() first_percent = data.find(b"%") if first_percent < 0: return bytes(data) hex_decode_table = _hex_decode_table() data_length = len(data) # stop at len - 2 because "%HH" decoding reads 2 extra bytes after '%' decode_limit = data_length - 2 output = bytearray(data_length) output[:first_percent] = data[:first_percent] input_index = first_percent output_index = first_percent while input_index < decode_limit: current_byte = data[input_index] if current_byte == 37: # ord('%') # Decoding "%HH" sequence # Step 1: read two hex characters after '%' # Example: "%4F" -> '4' and 'F' high_nibble = hex_decode_table[data[input_index + 1]] low_nibble = hex_decode_table[data[input_index + 2]] # Step 2: validate both characters are valid hex digits # hex_decode_table returns 255 for invalid input # bitwise OR catches any invalid nibble quickly if (high_nibble | low_nibble) != 255: # Step 3: combine two 4-bit nibbles into one byte # (high_nibble << 4) + low_nibble # Example: 0x4 and 0xF -> 0x4F output[output_index] = (high_nibble << 4) | low_nibble input_index += 3 # skip past "%HH" in input output_index += 1 # advance output position by one decoded byte continue output[output_index] = current_byte input_index += 1 output_index += 1 while input_index < data_length: # tail output[output_index] = data[input_index] input_index += 1 output_index += 1 return bytes(output[:output_index]) def _unquote_plus( data: bytes | bytearray | str, ) -> bytes: # This function is intentionally duplicated from `_unquote` for performance. # The duplication avoids extra branching for '+' handling in hot loop. if not data: return b"" if isinstance(data, str): # pragma: no cover data = data.encode() first_percent = data.find(b"%") first_plus = data.find(b"+") first_special = min(first_plus, first_percent) if first_special < 0: first_special = max(first_percent, first_plus) if first_special < 0: return bytes(data) hex_decode_table = _hex_decode_table() data_length = len(data) decode_limit = data_length - 2 output = bytearray(data_length) output[:first_special] = data[:first_special] input_index = first_special output_index = first_special while input_index < decode_limit: current_byte = data[input_index] if current_byte == 43: # ord('+') output[output_index] = 32 # ord(' ') input_index += 1 output_index += 1 continue if current_byte == 37: # ord('%') high_nibble = hex_decode_table[data[input_index + 1]] low_nibble = hex_decode_table[data[input_index + 2]] if (high_nibble | low_nibble) != 255: output[output_index] = (high_nibble << 4) | low_nibble input_index += 3 output_index += 1 continue output[output_index] = current_byte input_index += 1 output_index += 1 while input_index < data_length: # tail current_byte = data[input_index] if current_byte == 43: # ord('+') output[output_index] = 32 # ord(' ') else: output[output_index] = current_byte input_index += 1 output_index += 1 return bytes(output[:output_index]) def _parse_qs( qs: str | bytes, keep_blank_values: bool = False, separator: bytes = b"&", ) -> dict[bytes, list[bytes]]: """Reimplementation of urllib.parse.parse_qs which: - Doesn't use _coerce_args or _coerce_result - Works directly on bytes internally (no type coercion layer) - Returns bytes keys/values only""" if not qs: # pragma: no cover return {} if isinstance(qs, str): # pragma: no cover qs = qs.encode() result: dict[bytes, list[bytes]] = {} for field in qs.split(separator): if not field: continue key, sep, value = field.partition(b"=") if not keep_blank_values and (not sep or not value): continue key = _unquote_plus(key) value = _unquote_plus(value) if key in result: result[key].append(value) else: result[key] = [value] return result def _parse_qsl( qs: str | bytes, keep_blank_values: bool = False, separator: bytes = b"&", ) -> list[tuple[bytes, bytes]]: """Reimplementation of urllib.parse.parse_qsl which: - Doesn't use _coerce_args or _coerce_result - Works directly on bytes internally (no type coercion layer) - Returns only bytes tuples""" # This function is intentionally duplicated from `_parse_qs` for performance. if not qs: return [] if isinstance(qs, str): qs = qs.encode() result: list[tuple[bytes, bytes]] = [] for field in qs.split(separator): if not field: continue key, sep, value = field.partition(b"=") if not keep_blank_values and (not sep or not value): continue result.append((_unquote_plus(key), _unquote_plus(value))) return result def _urlencode(query: _QueryType, separator: bytes = b"&") -> bytes: if hasattr(query, "items"): # pragma: no cover query = query.items() # type: ignore[assignment] if not query: # pragma: no cover return b"" result: list[bytes] = [] tmp_buf = bytearray() for key, value in query: # type: ignore[str-unpack] _quote_into( key if isinstance(key, bytes) else str(key).encode(), output=tmp_buf, quote_plus=True, ) tmp_buf.append(61) # ord('=') _quote_into( value if isinstance(value, bytes) else str(value).encode(), output=tmp_buf, quote_plus=True, ) result.append(bytes(tmp_buf)) tmp_buf.clear() return separator.join(result) def _split_params(scheme: str, url: str) -> tuple[str, str]: """Split the params from the path, as urlib.parse.urlparse does.""" if scheme in _USES_PARAMS: # Only a ";" in the last segment starts the params; one in an earlier # segment is an ordinary path character. semi_idx = url.find(";", url.rfind("/") + 1) if semi_idx != -1: return url[:semi_idx], url[semi_idx + 1 :] return url, "" def _urlparse( url: str, scheme: str = "", allow_fragments: bool = True, ) -> ParseResult: """Reimplementation of urlib.parse.urlparse but without _coerce_args/_coerce_result.""" if not url: # pragma: no cover return ParseResult(scheme, "", "", "", "", "") scheme, netloc, url, query, fragment = _urlsplit(url, scheme, allow_fragments) url, params = _split_params(scheme, url) return ParseResult(scheme, netloc, url, params, query, fragment) def _urlunparse( scheme: str, netloc: str, url: str, params: str, query: str, fragment: str, ) -> str: """Reimplementation of urlib.parse.urlunparse but without _coerce_args/_coerce_result.""" if params: url = f"{url};{params}" return _urlunsplit(scheme, netloc, url, query, fragment) def _urlunsplit(scheme: str, netloc: str, url: str, query: str, fragment: str) -> str: """Reimplementation of urlib.parse.urlunsplit but without _coerce_args/_coerce_result.""" if netloc: if url and url[:1] != "/": url = f"/{url}" url = f"//{netloc}{url}" elif url[:2] == "//" or ( scheme and scheme in _USES_NETLOC and (not url or url[:1] == "/") ): url = f"//{url}" if scheme: scheme = f"{scheme}:" if query: query = f"?{query}" if fragment: fragment = f"#{fragment}" return f"{scheme}{url}{query}{fragment}" @dataclasses.dataclass(slots=True, eq=False, repr=False) class _SplitResult: # pylint: disable=too-many-instance-attributes scheme: str netloc: str path: str query: str fragment: str username: str | None = None password: str | None = None hostname: str | None = None port: str | int | None = None def __post_init__(self) -> None: if self.hostname is not None: hostname, delim, zone = self.hostname.partition("%") self.hostname = f"{hostname.lower()}{delim}{zone}" if self.port is not None: if isinstance(self.port, str) and not ( self.port.isascii() and self.port.isdigit() ): raise ValueError( f"Port could not be cast to integer value as {self.port}" ) self.port = int(self.port) if self.port not in range(65535 + 1): raise ValueError("Port out of range 0-65535") def __iter__(self) -> Generator[str]: yield self.scheme yield self.netloc yield self.path yield self.query yield self.fragment def __len__(self) -> int: return 5 # pragma: no cover def __getitem__(self, index: int) -> str: # pragma: no cover match index: case 0: return self.scheme case 1: return self.netloc case 2: return self.path case 3: return self.query case 4: return self.fragment raise IndexError def _checknetloc(netloc: str) -> None: """ Validate that NFKC normalization does not introduce reserved URL characters. Raises: ValueError: If normalization introduces reserved delimiters. """ if not netloc or netloc.isascii(): return # IDNA uses NFKC equivalence. Remove already-valid delimiters before # normalization so we only detect newly introduced ones. cleaned, normalized = _nfkc_netloc(netloc) if cleaned == normalized: return if _NETLOC_DELIMS_RE.search(normalized): raise ValueError( f"netloc {netloc!r} contains invalid characters under NFKC normalization" ) def _check_bracketed_netloc(netloc: str) -> None: """ Validate bracket usage in a URL netloc. Raises: ValueError: If bracket placement or host syntax is invalid. This is basically a backport of https://github.com/python/cpython/issues/105704 """ hostname_and_port = netloc.rpartition("@")[2] before_bracket, has_open_bracket, bracketed = hostname_and_port.partition("[") if has_open_bracket: # No data is allowed before '['. if before_bracket: raise ValueError("Invalid IPv6 URL") hostname, _, port = bracketed.partition("]") # Only ':' may follow ']'. if port and not port.startswith(":"): raise ValueError("Invalid IPv6 URL") # port validation done after, in `_SplitResult.__post_init__` else: hostname, _, _ = hostname_and_port.partition(":") _check_bracketed_host(hostname) def _check_bracketed_host(hostname: str) -> None: """ Validate a bracketed host according to RFC 3986 / WHATWG URL rules. Raises: ValueError: If the host is invalid. """ # IPvFuture: v.

if hostname.startswith(("v", "V")): if not _IPV_FUTURE_RE.fullmatch(hostname): raise ValueError("IPvFuture address is invalid") return # ip_address() raises ValueError if invalid. ip = ipaddress.ip_address(hostname) # Bracketed IPv4 literals are forbidden. if isinstance(ip, ipaddress.IPv4Address): raise ValueError("An IPv4 address cannot be in brackets") @functools.lru_cache def _urlsplit( # pylint: disable=too-many-locals,too-many-statements url: str, scheme: str = "", allow_fragments: bool = True, ) -> _SplitResult: """Reimplementation of urllib.parse.urlsplit which: - Doesn't use _coerce_args or _coerce_result - Does manual single-pass scanning instead of repeated .find/.split calls (where it's beneficial) - Have reduced string allocations by slicing once using computed indices - Avoids extra computations as much as possible """ if not url: return _SplitResult(scheme, "", "", "", "") # urllib.parse.urlsplit removes every ASCII tab and newline from anywhere in # the URL before parsing (the WHATWG "remove all ASCII tab or newline" # step). This reimplementation only stripped leading C0/space, so a tab or # newline embedded in the authority survived: parse_url("http://exa\tmple.com") # reported host "exa\tmple.com" while urlsplit and browsers drop the tab and # resolve "example.com". The membership checks keep the common tab-free path # free of translate calls and string allocations. if "\t" in url or "\n" in url or "\r" in url: url = url.translate(_ASCII_TAB_OR_NEWLINE_TRANSLATION_TABLE) if "\t" in scheme or "\n" in scheme or "\r" in scheme: scheme = scheme.translate(_ASCII_TAB_OR_NEWLINE_TRANSLATION_TABLE) url, scheme = url.lstrip(_C0_CONTROL_OR_SPACE), scheme.strip(_C0_CONTROL_OR_SPACE) netloc = query = fragment = "" if m := _SCHEME_RE.match(url): scheme = m.group(1).lower() url = url[m.end() :] # The URL living standard treats "\" like "/" for special-scheme URLs, but # only in the authority and path; a "\" in the query or fragment is left # alone. Without this, "http://evil.com\@good.com/" is read as userinfo # "evil.com\" plus host "good.com", while a browser ends the authority at # the "\" and connects to "evil.com". if scheme in _SPECIAL_SCHEMES and "\\" in url: cut = len(url) question_idx = url.find("?") if question_idx != -1: cut = question_idx hash_idx = url.find("#") if hash_idx != -1 and hash_idx < cut: cut = hash_idx url = url[:cut].replace("\\", "/") + url[cut:] # The scan skips the leading "//" of an authority; for URLs without an # authority it must start at 0, otherwise a "?" or "#" at index 0 or 1 # (e.g. relative URLs like "a?b" or "a#f") is never recorded. scan_start = 2 if url[:2] == "//" else 0 # Multiple str.find() are faster than a single manual loop. slash_pos = url.find("/", scan_start) question_pos = url.find("?", scan_start) hash_pos = url.find("#", scan_start) open_br_pos = url.find("[", scan_start) closing_br_pos = url.find("]", scan_start) if url[:2] == "//": delim = len(url) if 0 < slash_pos < delim: delim = slash_pos if 0 < question_pos < delim: delim = question_pos if 0 < hash_pos < delim: delim = hash_pos # Brackets only delimit an IPv6 host when they fall inside the # authority. A "[" or "]" in the path, query or fragment is an # ordinary character and must not drive IPv6 host parsing. if not 2 <= open_br_pos < delim: open_br_pos = -1 if not 2 <= closing_br_pos < delim: closing_br_pos = -1 if (open_br_pos != -1) != (closing_br_pos != -1): raise ValueError("Invalid IPv6 URL") netloc = url[2:delim] if open_br_pos != -1 and closing_br_pos != -1: _check_bracketed_netloc(netloc) url = url[delim:] if question_pos != -1: question_pos -= delim if hash_pos != -1: hash_pos -= delim _checknetloc(netloc) if allow_fragments and hash_pos != -1: url, fragment = url[:hash_pos], url[hash_pos + 1 :] if question_pos != -1: url, query = url[:question_pos], url[question_pos + 1 :] username = password = hostname = port = None userinfo, have_info, hostinfo = netloc.rpartition("@") if have_info: username, _, password = userinfo.partition(":") password = password if _ else None if open_br_pos != -1: hostname, _, port = hostinfo.partition("[")[2].partition("]") port = port.partition(":")[2] else: hostname, _, port = hostinfo.partition(":") return _SplitResult( scheme, netloc, url, query, fragment, username, password, hostname, port or None, ) def _url2pathname(url: str) -> str: """Reimplementation of urllib.request.url2pathname but with faster _unquote""" if not url: return "" # These branches are handled by `_urlparse` if url[:3] == "///": # pragma: no cover url = url[2:] elif url[:12] == "//localhost/": # pragma: no cover url = url[11:] if not _IS_WINDOWS: if "%" not in url: return url return _unquote(url).decode(_FS_ENCODING, _FS_ERRORS) if url[:3] == "///": url = url[1:] url = url.replace(":", "|") if "|" not in url: return _unquote(url.replace("/", "\\").encode()).decode( _FS_ENCODING, _FS_ERRORS ) comp = url.split("|") if len(comp) != 2 or comp[0][-1] not in string.ascii_letters: raise OSError(f"Bad URL: {url}") drive = comp[0][-1].upper() tail = _unquote(comp[1].replace("/", "\\")).decode(_FS_ENCODING, _FS_ERRORS) return f"{drive}:{tail}" @functools.lru_cache def _idna(input_string: str) -> tuple[bytes, str]: """Cached IDNA encoding using Python's built-in 'idna' codec. IDNA processing in CPython is implemented in pure Python (not C), which makes it relatively slow and allocation-heavy. The only lower-level optimisation involved is Unicode normalization (NFKC), which may use optimized internal paths, but IDNA itself remains Python-level logic. """ if input_string.isascii(): return input_string.encode(), input_string _, normalized = _nfkc_netloc(input_string) encoded = normalized.encode("idna") return encoded, encoded.decode() def _idna_bytes(input_string: str) -> bytes: return _idna(input_string)[0] @functools.lru_cache def _nfkc_netloc(netloc: str) -> tuple[str, str]: cleaned = netloc.translate(_NETLOC_STRIP_CHARS) normalized = unicodedata.normalize("NFKC", cleaned) return cleaned, normalized scrapy-w3lib-d6b4a87/w3lib/_util.py000066400000000000000000000063161525715767700172140ustar00rootroot00000000000000from __future__ import annotations import re from functools import lru_cache from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterable def to_unicode( text: str | bytes, encoding: str | None = None, errors: str = "strict" ) -> str: """Return the unicode representation of a bytes object `text`. If `text` is already an unicode object, return it as-is.""" if isinstance(text, str): return text if not isinstance(text, (bytes, str)): raise TypeError( f"to_unicode must receive bytes or str, got {type(text).__name__}" ) if encoding is None: encoding = "utf-8" return text.decode(encoding, errors) _ASCII = bytes(range(128)) _ASCII_TEXT = _ASCII.decode() @lru_cache(maxsize=64) def _ascii_compatible(encoding: str | None) -> bool: """Return whether ASCII bytes decode to the same ASCII characters under *encoding*. Unknown encodings are reported as not compatible. """ try: return _ASCII.decode(encoding or "utf-8", "replace") == _ASCII_TEXT except LookupError: return False # Bytes that an encoding can drop when decoding, dividing a character # sequence without leaving a trace in the text: ESC ( B redesignates ASCII # while ASCII is already in use, and SO and SI shift between character sets. _DROPPED = (b"\x1b(B", b"\x0e", b"\x0f") @lru_cache(maxsize=64) def _scannable(encoding: str | None) -> bool: r"""Return whether every character sequence of a document written in *encoding* is a byte sequence of its undecoded bytes, so that markup that the bytes do not contain is markup that the document does not contain. It takes ASCII compatibility, which makes ASCII characters their own bytes, and an encoding that cannot write those bytes apart, e.g. ``b"[^\s<>/=]+) # name (?:\s*=\s*(?:"(?P[^"]*)"|'(?P[^']*)'|(?P[^\s"'>]*)))?""", re.VERBOSE, ) def iter_tag_attributes(attrs: str) -> Iterable[tuple[str, str]]: """Yield ``(name, value)`` for every attribute with a value in ``attrs``, the text of one tag after its name, in order. ``name`` is lowercased, and ``value`` has its quotes removed, if any. """ # finditer() matches one attribute at a time, from where the previous one # ended, so a crafted tag cannot make it backtrack across attributes. for attr in _attr_re.finditer(attrs): # A valueless attribute matches the name group and nothing after it. if attr.lastindex == 1: continue name, double, single, bare = attr.groups() # Exactly one value group matched; the last "" covers all three being # empty, which an empty value in any quoting style produces. yield name.lower(), double or single or bare or "" scrapy-w3lib-d6b4a87/w3lib/encoding.py000066400000000000000000000357731525715767700176770ustar00rootroot00000000000000""" Functions for handling encoding of web pages """ from __future__ import annotations import codecs import encodings import re from functools import lru_cache from typing import TYPE_CHECKING, cast from w3lib._util import iter_tag_attributes if TYPE_CHECKING: from collections.abc import Callable from w3lib._types import AnyUnicodeError # The value ends at whitespace, ";", "," or the end of the header. Comma is # not parameter syntax; stopping the value at "," approximates Fetch's # "extract a MIME type" for comma-joined duplicate headers, keeping the first # charset rather than the last valid MIME type's. _HEADER_ENCODING_RE = re.compile( r"(?:^|;)[ \t]*charset=" r'(?:"([\w-]+)"|([\w-]+))' r"(?![^\s;,])", re.IGNORECASE, ) # https://mimesniff.spec.whatwg.org/commit-snapshots/39aa53511b13953d84fef8d4131d6f61d0ccbde6/#parse-a-mime-type # Parameters are ";"-separated name=value pairs whose value is either a token # or a quoted-string, and a quoted-string is opaque # (https://fetch.spec.whatwg.org/commit-snapshots/586cd2a44c2a865b37c166dc0740f3fb8bb220d6/#collect-an-http-quoted-string), # so it has to be consumed as a whole: a "charset=" written inside one belongs # to that value and is not a parameter of its own. _HEADER_PARAMETER_RE = re.compile( r"(?:^|;)[ \t]*(?P[^\s;=]+)=" r'(?:"(?P[^"\\]*(?:\\.[^"\\]*)*)"(?![^\s;,])' r"|(?P[^;,\s]*))" ) _ENCODING_LABEL_RE = re.compile(r"[\w-]+") def _quoted_aware_charset(content_type: str) -> str | None: for match in _HEADER_PARAMETER_RE.finditer(content_type): if match.group("name").lower() != "charset": continue label = match.group("quoted") if label is None: label = match.group("token") if _ENCODING_LABEL_RE.fullmatch(label): return resolve_encoding(label) return None def http_content_type_encoding(content_type: str | None) -> str | None: """Extract the encoding in the content-type header >>> import w3lib.encoding >>> w3lib.encoding.http_content_type_encoding("Content-Type: text/html; charset=ISO-8859-4") 'iso8859-4' """ if content_type: match = _HEADER_ENCODING_RE.search(content_type) if match: # A match inside a quoted-string must be preceded by that string's # opening quote, so if no '"' precedes it the fast answer is # correct; only otherwise walk the parameters. if content_type.find('"', 0, match.start()) < 0: return resolve_encoding(match.group(1) or match.group(2)) return _quoted_aware_charset(content_type) return None # Scan for the first meta tag or xml declaration, and stop the search if a # body tag is encountered. # Comments are skipped by the WHATWG prescan before it looks for a meta # charset, so a declaration written inside one is not honored (and a commented # body tag does not stop the scan): they are consumed as an alternative of the # scan itself, as get_base_url() does, rather than stripped out beforehand, so # the text on either side of a comment is never spliced into a tag. # A meta tag is consumed with its quoted attribute values whole, so a quoted # ">" does not end it and a quoted "|$) # comment | <\s*meta(?=[\s/])(?P(?:[^<>=]|=\s*(?:"[^"]*"|'[^']*')?)*) # meta tag | <\?xml\s(?P[^<>]*) # XML declaration | <\s*(?Pbody) # start of the body tag """, re.IGNORECASE | re.DOTALL | re.VERBOSE, ) # The pragma attribute, however spelled (e.g. #155 has httpequiv="ContentType"). _HTTP_EQUIV_NAMES = frozenset({"http-equiv", "http_equiv", "httpequiv"}) # Its value must name the content-type pragma, also however spelled. _CONTENT_TYPE_PRAGMA_RE = re.compile(r"content[-_ ]?type", re.IGNORECASE) # A "charset=" wherever it occurs in a content attribute value, as in the # WHATWG "extract a character encoding from a meta element" algorithm. _CONTENT_CHARSET_RE = re.compile( r"""charset\s*=\s*["']?\s*(?P