diff --git a/.bandit.yml b/.bandit.yml
index 243379b0b..2aae8a0aa 100644
--- a/.bandit.yml
+++ b/.bandit.yml
@@ -1,5 +1,6 @@
skips:
- B101
+- B113 # https://github.com/PyCQA/bandit/issues/1010
- B105
- B301
- B303
@@ -8,6 +9,7 @@ skips:
- B311
- B320
- B321
+- B324
- B402 # https://github.com/scrapy/scrapy/issues/4180
- B403
- B404
@@ -16,3 +18,4 @@ skips:
- B503
- B603
- B605
+exclude_dirs: ['tests']
diff --git a/.bumpversion.cfg b/.bumpversion.cfg
index 3c1c8f891..f76bf783d 100644
--- a/.bumpversion.cfg
+++ b/.bumpversion.cfg
@@ -1,5 +1,5 @@
[bumpversion]
-current_version = 2.3.0
+current_version = 2.11.0
commit = True
tag = True
tag_name = {new_version}
diff --git a/.coveragerc b/.coveragerc
index 02acbff8e..ad0ee0f6c 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -3,3 +3,4 @@ branch = true
include = scrapy/*
omit =
tests/*
+disable_warnings = include-ignored
diff --git a/.flake8 b/.flake8
new file mode 100644
index 000000000..544d72956
--- /dev/null
+++ b/.flake8
@@ -0,0 +1,22 @@
+[flake8]
+
+max-line-length = 119
+ignore = W503, E203
+
+exclude =
+ docs/conf.py
+
+per-file-ignores =
+# Exclude files that are meant to provide top-level imports
+# E402: Module level import not at top of file
+# F401: Module imported but unused
+ scrapy/__init__.py:E402
+ scrapy/core/downloader/handlers/http.py:F401
+ scrapy/http/__init__.py:F401
+ scrapy/linkextractors/__init__.py:E402,F401
+ scrapy/selector/__init__.py:F401
+ scrapy/spiders/__init__.py:E402,F401
+
+ # Issues pending a review:
+ scrapy/utils/url.py:F403,F405
+ tests/test_loader.py:E741
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
new file mode 100644
index 000000000..dbcebfa0a
--- /dev/null
+++ b/.git-blame-ignore-revs
@@ -0,0 +1,7 @@
+# .git-blame-ignore-revs
+# adding black formatter to all the code
+e211ec0aa26ecae0da8ae55d064ea60e1efe4d0d
+# re applying black to the code with default line length
+303f0a70fcf8067adf0a909c2096a5009162383a
+# reaplying black again and removing line length on pre-commit black config
+c5cdd0d30ceb68ccba04af0e71d1b8e6678e2962
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md
new file mode 100644
index 000000000..63cae77e7
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.md
@@ -0,0 +1,13 @@
+---
+name: Question / Help
+about: Ask a question about Scrapy or ask for help with your Scrapy code.
+---
+
+Thanks for taking an interest in Scrapy!
+
+The Scrapy GitHub issue tracker is not meant for questions or help. Please ask
+for help in the [Scrapy community resources](https://scrapy.org/community/)
+instead.
+
+The GitHub issue tracker's purpose is to deal with bug reports and feature
+requests for the project itself.
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml
new file mode 100644
index 000000000..d6fc0f6c5
--- /dev/null
+++ b/.github/workflows/checks.yml
@@ -0,0 +1,46 @@
+name: Checks
+on: [push, pull_request]
+
+concurrency:
+ group: ${{github.workflow}}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ checks:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - python-version: "3.12"
+ env:
+ TOXENV: pylint
+ - python-version: 3.8
+ env:
+ TOXENV: typing
+ - python-version: "3.11" # Keep in sync with .readthedocs.yml
+ env:
+ TOXENV: docs
+ - python-version: "3.12"
+ env:
+ TOXENV: twinecheck
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Run check
+ env: ${{ matrix.env }}
+ run: |
+ pip install -U tox
+ tox
+
+ pre-commit:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: pre-commit/action@v3.0.0
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 000000000..affaa32a5
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,25 @@
+name: Publish
+on:
+ push:
+ tags:
+ - '[0-9]+.[0-9]+.[0-9]+'
+
+concurrency:
+ group: ${{github.workflow}}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v4
+ with:
+ python-version: 3.12
+ - run: |
+ pip install --upgrade build twine
+ python -m build
+ - name: Publish to PyPI
+ uses: pypa/gh-action-pypi-publish@v1.6.4
+ with:
+ password: ${{ secrets.PYPI_TOKEN }}
diff --git a/.github/workflows/tests-macos.yml b/.github/workflows/tests-macos.yml
new file mode 100644
index 000000000..252176464
--- /dev/null
+++ b/.github/workflows/tests-macos.yml
@@ -0,0 +1,30 @@
+name: macOS
+on: [push, pull_request]
+
+concurrency:
+ group: ${{github.workflow}}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ tests:
+ runs-on: macos-11
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Run tests
+ run: |
+ pip install -U tox
+ tox -e py
+
+ - name: Upload coverage report
+ run: bash <(curl -s https://codecov.io/bash)
diff --git a/.github/workflows/tests-ubuntu.yml b/.github/workflows/tests-ubuntu.yml
new file mode 100644
index 000000000..f50a4d104
--- /dev/null
+++ b/.github/workflows/tests-ubuntu.yml
@@ -0,0 +1,82 @@
+name: Ubuntu
+on: [push, pull_request]
+
+concurrency:
+ group: ${{github.workflow}}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - python-version: 3.9
+ env:
+ TOXENV: py
+ - python-version: "3.10"
+ env:
+ TOXENV: py
+ - python-version: "3.11"
+ env:
+ TOXENV: py
+ - python-version: "3.12"
+ env:
+ TOXENV: py
+ - python-version: "3.12"
+ env:
+ TOXENV: asyncio
+ - python-version: pypy3.9
+ env:
+ TOXENV: pypy3
+ - python-version: pypy3.10
+ env:
+ TOXENV: pypy3
+
+ # pinned deps
+ - python-version: 3.8.17
+ env:
+ TOXENV: pinned
+ - python-version: 3.8.17
+ env:
+ TOXENV: asyncio-pinned
+ - python-version: pypy3.8
+ env:
+ TOXENV: pypy3-pinned
+ - python-version: 3.8.17
+ env:
+ TOXENV: extra-deps-pinned
+ - python-version: 3.8.17
+ env:
+ TOXENV: botocore-pinned
+
+ - python-version: "3.12"
+ env:
+ TOXENV: extra-deps
+ - python-version: "3.12"
+ env:
+ TOXENV: botocore
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install system libraries
+ if: contains(matrix.python-version, 'pypy') || contains(matrix.env.TOXENV, 'pinned')
+ run: |
+ sudo apt-get update
+ sudo apt-get install libxml2-dev libxslt-dev
+
+ - name: Run tests
+ env: ${{ matrix.env }}
+ run: |
+ pip install -U tox
+ tox
+
+ - name: Upload coverage report
+ run: bash <(curl -s https://codecov.io/bash)
diff --git a/.github/workflows/tests-windows.yml b/.github/workflows/tests-windows.yml
new file mode 100644
index 000000000..757d62285
--- /dev/null
+++ b/.github/workflows/tests-windows.yml
@@ -0,0 +1,46 @@
+name: Windows
+on: [push, pull_request]
+
+concurrency:
+ group: ${{github.workflow}}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ tests:
+ runs-on: windows-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - python-version: 3.8
+ env:
+ TOXENV: windows-pinned
+ - python-version: 3.9
+ env:
+ TOXENV: py
+ - python-version: "3.10"
+ env:
+ TOXENV: py
+ - python-version: "3.11"
+ env:
+ TOXENV: py
+ - python-version: "3.12"
+ env:
+ TOXENV: py
+ - python-version: "3.12"
+ env:
+ TOXENV: asyncio
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Run tests
+ env: ${{ matrix.env }}
+ run: |
+ pip install -U tox
+ tox
diff --git a/.gitignore b/.gitignore
index 795e2605e..6c5c50e08 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,8 @@ htmlcov/
.coverage
.pytest_cache/
.coverage.*
+coverage.*
+test-output.*
.cache/
.mypy_cache/
/tests/keys/localhost.crt
@@ -21,3 +23,6 @@ htmlcov/
# Windows
Thumbs.db
+
+# OSX miscellaneous
+.DS_Store
\ No newline at end of file
diff --git a/.isort.cfg b/.isort.cfg
new file mode 100644
index 000000000..f238bf7ea
--- /dev/null
+++ b/.isort.cfg
@@ -0,0 +1,2 @@
+[settings]
+profile = black
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..0cff5cc73
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,24 @@
+repos:
+- repo: https://github.com/PyCQA/bandit
+ rev: 1.7.5
+ hooks:
+ - id: bandit
+ args: [-r, -c, .bandit.yml]
+- repo: https://github.com/PyCQA/flake8
+ rev: 6.1.0
+ hooks:
+ - id: flake8
+- repo: https://github.com/psf/black.git
+ rev: 23.9.1
+ hooks:
+ - id: black
+- repo: https://github.com/pycqa/isort
+ rev: 5.12.0
+ hooks:
+ - id: isort
+- repo: https://github.com/adamchainz/blacken-docs
+ rev: 1.16.0
+ hooks:
+ - id: blacken-docs
+ additional_dependencies:
+ - black==23.9.1
diff --git a/.readthedocs.yml b/.readthedocs.yml
index e4d3f02cc..e71d34f3a 100644
--- a/.readthedocs.yml
+++ b/.readthedocs.yml
@@ -3,10 +3,15 @@ formats: all
sphinx:
configuration: docs/conf.py
fail_on_warning: true
+
+build:
+ os: ubuntu-20.04
+ tools:
+ # For available versions, see:
+ # https://docs.readthedocs.io/en/stable/config-file/v2.html#build-tools-python
+ python: "3.11" # Keep in sync with .github/workflows/checks.yml
+
python:
- # For available versions, see:
- # https://docs.readthedocs.io/en/stable/config-file/v2.html#build-image
- version: 3.7 # Keep in sync with .travis.yml
install:
- requirements: docs/requirements.txt
- path: .
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index b883c5b78..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,75 +0,0 @@
-language: python
-dist: xenial
-branches:
- only:
- - master
- - /^\d\.\d+$/
- - /^\d\.\d+\.\d+(rc\d+|\.dev\d+)?$/
-matrix:
- include:
- - env: TOXENV=security
- python: 3.8
- - env: TOXENV=flake8
- python: 3.8
- - env: TOXENV=pylint
- python: 3.8
- - env: TOXENV=docs
- python: 3.7 # Keep in sync with .readthedocs.yml
- - env: TOXENV=typing
- python: 3.8
-
- - env: TOXENV=pinned
- python: 3.6.1
- - env: TOXENV=asyncio-pinned
- python: 3.6.1
- - env: TOXENV=pypy3-pinned PYPY_VERSION=3.6-v7.2.0
-
- - env: TOXENV=py
- python: 3.6
- - env: TOXENV=pypy3 PYPY_VERSION=3.6-v7.3.1
-
- - env: TOXENV=py
- python: 3.7
-
- - env: TOXENV=py PYPI_RELEASE_JOB=true
- python: 3.8
- dist: bionic
- - env: TOXENV=extra-deps
- python: 3.8
- dist: bionic
- - env: TOXENV=asyncio
- python: 3.8
- dist: bionic
-install:
- - |
- if [[ ! -z "$PYPY_VERSION" ]]; then
- export PYPY_VERSION="pypy$PYPY_VERSION-linux64"
- wget "https://downloads.python.org/pypy/${PYPY_VERSION}.tar.bz2"
- tar -jxf ${PYPY_VERSION}.tar.bz2
- virtualenv --python="$PYPY_VERSION/bin/pypy3" "$HOME/virtualenvs/$PYPY_VERSION"
- source "$HOME/virtualenvs/$PYPY_VERSION/bin/activate"
- fi
- - pip install -U tox twine wheel codecov
-
-script: tox
-after_success:
- - codecov
-notifications:
- irc:
- use_notice: true
- skip_join: true
- channels:
- - irc.freenode.org#scrapy
-cache:
- directories:
- - $HOME/.cache/pip
-deploy:
- provider: pypi
- distributions: "sdist bdist_wheel"
- user: scrapy
- password:
- secure: JaAKcy1AXWXDK3LXdjOtKyaVPCSFoCGCnW15g4f65E/8Fsi9ZzDfmBa4Equs3IQb/vs/if2SVrzJSr7arN7r9Z38Iv1mUXHkFAyA3Ym8mThfABBzzcUWEQhIHrCX0Tdlx9wQkkhs+PZhorlmRS4gg5s6DzPaeA2g8SCgmlRmFfA=
- on:
- tags: true
- repo: scrapy/scrapy
- condition: "$PYPI_RELEASE_JOB == true && $TRAVIS_TAG =~ ^[0-9]+[.][0-9]+[.][0-9]+(rc[0-9]+|[.]dev[0-9]+)?$"
diff --git a/AUTHORS b/AUTHORS
index bcaa1ecd3..9706adf42 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,8 +1,8 @@
Scrapy was brought to life by Shane Evans while hacking a scraping framework
prototype for Mydeco (mydeco.com). It soon became maintained, extended and
improved by Insophia (insophia.com), with the initial sponsorship of Mydeco to
-bootstrap the project. In mid-2011, Scrapinghub became the new official
-maintainer.
+bootstrap the project. In mid-2011, Scrapinghub (now Zyte) became the new
+official maintainer.
Here is the list of the primary authors & contributors:
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index d1cd3e517..3c8e4d1b5 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,74 +1,133 @@
+
# Contributor Covenant Code of Conduct
## Our Pledge
-In the interest of fostering an open and welcoming environment, we as
-contributors and maintainers pledge to make participation in our project and
-our community a harassment-free experience for everyone, regardless of age, body
-size, disability, ethnicity, gender identity and expression, level of experience,
-nationality, personal appearance, race, religion, or sexual identity and
-orientation.
+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 creating a positive environment
-include:
+Examples of behavior that contributes to a positive environment for our
+community include:
-* Using welcoming and inclusive language
-* Being respectful of differing viewpoints and experiences
-* Gracefully accepting constructive criticism
-* Focusing on what is best for the community
-* Showing empathy towards other community members
+* 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 by participants include:
+Examples of unacceptable behavior include:
-* The use of sexualized language or imagery and unwelcome sexual attention or
- advances
-* Trolling, insulting/derogatory comments, and personal or political attacks
+* 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 electronic
- address, without explicit permission
+* 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
-## Our Responsibilities
+## Enforcement Responsibilities
-Project maintainers are responsible for clarifying the standards of acceptable
-behavior and are expected to take appropriate and fair corrective action in
-response to any instances of unacceptable behavior.
+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.
-Project maintainers 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, or to ban temporarily or
-permanently any contributor for other behaviors 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 both within project spaces and in public spaces
-when an individual is representing the project or its community. Examples of
-representing a project or community include using an official project e-mail
-address, posting via an official social media account, or acting as an appointed
-representative at an online or offline event. Representation of a project may be
-further defined and clarified by project maintainers.
+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 by contacting the project team at opensource@scrapinghub.com. All
-complaints will be reviewed and investigated and will result in a response that
-is deemed necessary and appropriate to the circumstances. The project team is
-obligated to maintain confidentiality with regard to the reporter of an incident.
-Further details of specific enforcement policies may be posted separately.
+reported to the community leaders responsible for enforcement at
+opensource@zyte.com.
+All complaints will be reviewed and investigated promptly and fairly.
-Project maintainers who do not follow or enforce the Code of Conduct in good
-faith may face temporary or permanent repercussions as determined by other
-members of the project's leadership.
+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 1.4,
-available at [http://contributor-covenant.org/version/1/4][version].
+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].
-[homepage]: http://contributor-covenant.org
-[version]: http://contributor-covenant.org/version/1/4/
+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
diff --git a/INSTALL b/INSTALL
deleted file mode 100644
index 06e812936..000000000
--- a/INSTALL
+++ /dev/null
@@ -1,4 +0,0 @@
-For information about installing Scrapy see:
-
-* docs/intro/install.rst (local file)
-* https://docs.scrapy.org/en/latest/intro/install.html (online version)
diff --git a/INSTALL.md b/INSTALL.md
new file mode 100644
index 000000000..495413f97
--- /dev/null
+++ b/INSTALL.md
@@ -0,0 +1,4 @@
+For information about installing Scrapy see:
+
+* [Local docs](docs/intro/install.rst)
+* [Online docs](https://docs.scrapy.org/en/latest/intro/install.html)
diff --git a/MANIFEST.in b/MANIFEST.in
index ae7db51fa..4920dc0c3 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -7,6 +7,7 @@ include NEWS
include scrapy/VERSION
include scrapy/mime.types
+include scrapy/py.typed
include codecov.yml
include conftest.py
diff --git a/README.rst b/README.rst
index a8f2ba52b..14adff648 100644
--- a/README.rst
+++ b/README.rst
@@ -1,3 +1,6 @@
+.. image:: https://scrapy.org/img/scrapylogo.png
+ :target: https://scrapy.org/
+
======
Scrapy
======
@@ -10,9 +13,18 @@ Scrapy
:target: https://pypi.python.org/pypi/Scrapy
:alt: Supported Python Versions
-.. image:: https://img.shields.io/travis/scrapy/scrapy/master.svg
- :target: https://travis-ci.org/scrapy/scrapy
- :alt: Build Status
+.. image:: https://github.com/scrapy/scrapy/workflows/Ubuntu/badge.svg
+ :target: https://github.com/scrapy/scrapy/actions?query=workflow%3AUbuntu
+ :alt: Ubuntu
+
+.. .. image:: https://github.com/scrapy/scrapy/workflows/macOS/badge.svg
+ .. :target: https://github.com/scrapy/scrapy/actions?query=workflow%3AmacOS
+ .. :alt: macOS
+
+
+.. image:: https://github.com/scrapy/scrapy/workflows/Windows/badge.svg
+ :target: https://github.com/scrapy/scrapy/actions?query=workflow%3AWindows
+ :alt: Windows
.. image:: https://img.shields.io/badge/wheel-yes-brightgreen.svg
:target: https://pypi.python.org/pypi/Scrapy
@@ -30,23 +42,32 @@ Scrapy
Overview
========
-Scrapy is a fast high-level web crawling and web scraping framework, used to
+Scrapy is a BSD-licensed fast high-level web crawling and web scraping framework, used to
crawl websites and extract structured data from their pages. It can be used for
a wide range of purposes, from data mining to monitoring and automated testing.
+Scrapy is maintained by Zyte_ (formerly Scrapinghub) and `many other
+contributors`_.
+
+.. _many other contributors: https://github.com/scrapy/scrapy/graphs/contributors
+.. _Zyte: https://www.zyte.com/
+
Check the Scrapy homepage at https://scrapy.org for more information,
including a list of features.
+
Requirements
============
-* Python 3.6+
+* Python 3.8+
* Works on Linux, Windows, macOS, BSD
Install
=======
-The quick way::
+The quick way:
+
+.. code:: bash
pip install scrapy
@@ -77,11 +98,10 @@ See https://docs.scrapy.org/en/master/contributing.html for details.
Code of Conduct
---------------
-Please note that this project is released with a Contributor Code of Conduct
-(see https://github.com/scrapy/scrapy/blob/master/CODE_OF_CONDUCT.md).
+Please note that this project is released with a Contributor `Code of Conduct `_.
By participating in this project you agree to abide by its terms.
-Please report unacceptable behavior to opensource@scrapinghub.com.
+Please report unacceptable behavior to opensource@zyte.com.
Companies using Scrapy
======================
@@ -91,4 +111,4 @@ See https://scrapy.org/companies/ for a list.
Commercial Support
==================
-See https://scrapy.org/support/ for details.
+See https://scrapy.org/support/ for details.
\ No newline at end of file
diff --git a/artwork/README.rst b/artwork/README.rst
index 8a1028cde..c1880ef6c 100644
--- a/artwork/README.rst
+++ b/artwork/README.rst
@@ -2,19 +2,19 @@
Scrapy artwork
==============
-This folder contains Scrapy artwork resources such as logos and fonts.
+This folder contains the Scrapy artwork resources such as logos and fonts.
scrapy-logo.jpg
---------------
-Main Scrapy logo, in JPEG format.
+The main Scrapy logo, in JPEG format.
qlassik.zip
-----------
-Font used for Scrapy logo. Homepage: https://www.dafont.com/qlassik.font
+The font used for the Scrapy logo. Homepage: https://www.dafont.com/qlassik.font
scrapy-blog.logo.xcf
--------------------
-The logo used in Scrapy blog, in Gimp format.
+The logo used in the Scrapy blog, in Gimp format.
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
deleted file mode 100644
index c03e258c7..000000000
--- a/azure-pipelines.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-variables:
- TOXENV: py
-pool:
- vmImage: 'windows-latest'
-strategy:
- matrix:
- Python36:
- python.version: '3.6'
- TOXENV: windows-pinned
- Python37:
- python.version: '3.7'
- Python38:
- python.version: '3.8'
-steps:
-- task: UsePythonVersion@0
- inputs:
- versionSpec: '$(python.version)'
- displayName: 'Use Python $(python.version)'
-- script: |
- pip install -U tox twine wheel codecov
- tox
- displayName: 'Run test suite'
diff --git a/conftest.py b/conftest.py
index 68b855c08..2bfa46f5a 100644
--- a/conftest.py
+++ b/conftest.py
@@ -1,27 +1,46 @@
+import platform
+import sys
from pathlib import Path
import pytest
+from twisted import version as twisted_version
+from twisted.python.versions import Version
+from twisted.web.http import H2_ENABLED
+from scrapy.utils.reactor import install_reactor
from tests.keys import generate_keys
def _py_files(folder):
- return (str(p) for p in Path(folder).rglob('*.py'))
+ return (str(p) for p in Path(folder).rglob("*.py"))
collect_ignore = [
# not a test, but looks like a test
"scrapy/utils/testsite.py",
+ "tests/ftpserver.py",
+ "tests/mockserver.py",
+ "tests/pipelines.py",
+ "tests/spiders.py",
# contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess
*_py_files("tests/CrawlerProcess"),
# contains scripts to be run by tests/test_crawler.py::CrawlerRunnerSubprocess
*_py_files("tests/CrawlerRunner"),
]
-for line in open('tests/ignores.txt'):
- file_path = line.strip()
- if file_path and file_path[0] != '#':
- collect_ignore.append(file_path)
+with Path("tests/ignores.txt").open(encoding="utf-8") as reader:
+ for line in reader:
+ file_path = line.strip()
+ if file_path and file_path[0] != "#":
+ collect_ignore.append(file_path)
+
+if not H2_ENABLED:
+ collect_ignore.extend(
+ (
+ "scrapy/core/downloader/handlers/http2.py",
+ *_py_files("scrapy/core/http2"),
+ )
+ )
@pytest.fixture()
@@ -30,17 +49,15 @@ def chdir(tmpdir):
tmpdir.chdir()
-def pytest_collection_modifyitems(session, config, items):
- # Avoid executing tests when executing `--flake8` flag (pytest-flake8)
- try:
- from pytest_flake8 import Flake8Item
- if config.getoption('--flake8'):
- items[:] = [item for item in items if isinstance(item, Flake8Item)]
- except ImportError:
- pass
+def pytest_addoption(parser):
+ parser.addoption(
+ "--reactor",
+ default="default",
+ choices=["default", "asyncio"],
+ )
-@pytest.fixture(scope='class')
+@pytest.fixture(scope="class")
def reactor_pytest(request):
if not request.cls:
# doctests
@@ -51,8 +68,36 @@ def reactor_pytest(request):
@pytest.fixture(autouse=True)
def only_asyncio(request, reactor_pytest):
- if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio':
- pytest.skip('This test is only run with --reactor=asyncio')
+ if request.node.get_closest_marker("only_asyncio") and reactor_pytest != "asyncio":
+ pytest.skip("This test is only run with --reactor=asyncio")
+
+
+@pytest.fixture(autouse=True)
+def only_not_asyncio(request, reactor_pytest):
+ if (
+ request.node.get_closest_marker("only_not_asyncio")
+ and reactor_pytest == "asyncio"
+ ):
+ pytest.skip("This test is only run without --reactor=asyncio")
+
+
+@pytest.fixture(autouse=True)
+def requires_uvloop(request):
+ if not request.node.get_closest_marker("requires_uvloop"):
+ return
+ if sys.implementation.name == "pypy":
+ pytest.skip("uvloop does not support pypy properly")
+ if platform.system() == "Windows":
+ pytest.skip("uvloop does not support Windows")
+ if twisted_version == Version("twisted", 21, 2, 0):
+ pytest.skip("https://twistedmatrix.com/trac/ticket/10106")
+ if sys.version_info >= (3, 12):
+ pytest.skip("uvloop doesn't support Python 3.12 yet")
+
+
+def pytest_configure(config):
+ if config.getoption("--reactor") == "asyncio":
+ install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor")
# Generate localhost certificate files, needed by some tests
diff --git a/docs/Makefile b/docs/Makefile
index ff68bf1ae..48401bac8 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -8,7 +8,7 @@ PYTHON = python
SPHINXOPTS =
PAPER =
SOURCES =
-SHELL = /bin/bash
+SHELL = /usr/bin/env bash
ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees \
-D latex_elements.papersize=$(PAPER) \
@@ -86,8 +86,8 @@ coverage: BUILDER = coverage
coverage: build
htmlview: html
- $(PYTHON) -c "import webbrowser, os; webbrowser.open('file://' + \
- os.path.realpath('build/html/index.html'))"
+ $(PYTHON) -c "import webbrowser; from pathlib import Path; \
+ webbrowser.open(Path('build/html/index.html').resolve().as_uri())"
clean:
-rm -rf build/*
diff --git a/docs/README.rst b/docs/README.rst
index 0b7afa548..36dd5aea4 100644
--- a/docs/README.rst
+++ b/docs/README.rst
@@ -43,7 +43,7 @@ This command will fire up your default browser and open the main page of your
Start over
----------
-To cleanup all generated documentation files and start from scratch run::
+To clean up all generated documentation files and start from scratch run::
make clean
diff --git a/docs/_ext/scrapydocs.py b/docs/_ext/scrapydocs.py
index 640660943..c23a89089 100644
--- a/docs/_ext/scrapydocs.py
+++ b/docs/_ext/scrapydocs.py
@@ -1,8 +1,9 @@
-from docutils.parsers.rst.roles import set_classes
+from operator import itemgetter
+
from docutils import nodes
from docutils.parsers.rst import Directive
+from docutils.parsers.rst.roles import set_classes
from sphinx.util.nodes import make_refnode
-from operator import itemgetter
class settingslist_node(nodes.General, nodes.Element):
@@ -11,15 +12,15 @@ class settingslist_node(nodes.General, nodes.Element):
class SettingsListDirective(Directive):
def run(self):
- return [settingslist_node('')]
+ return [settingslist_node("")]
def is_setting_index(node):
- if node.tagname == 'index':
+ if node.tagname == "index" and node["entries"]:
# index entries for setting directives look like:
# [('pair', 'SETTING_NAME; setting', 'std:setting-SETTING_NAME', '')]
- entry_type, info, refid = node['entries'][0][:3]
- return entry_type == 'pair' and info.endswith('; setting')
+ entry_type, info, refid = node["entries"][0][:3]
+ return entry_type == "pair" and info.endswith("; setting")
return False
@@ -30,14 +31,14 @@ def get_setting_target(node):
def get_setting_name_and_refid(node):
"""Extract setting name from directive index node"""
- entry_type, info, refid = node['entries'][0][:3]
- return info.replace('; setting', ''), refid
+ entry_type, info, refid = node["entries"][0][:3]
+ return info.replace("; setting", ""), refid
def collect_scrapy_settings_refs(app, doctree):
env = app.builder.env
- if not hasattr(env, 'scrapy_all_settings'):
+ if not hasattr(env, "scrapy_all_settings"):
env.scrapy_all_settings = []
for node in doctree.traverse(is_setting_index):
@@ -46,18 +47,23 @@ def collect_scrapy_settings_refs(app, doctree):
setting_name, refid = get_setting_name_and_refid(node)
- env.scrapy_all_settings.append({
- 'docname': env.docname,
- 'setting_name': setting_name,
- 'refid': refid,
- })
+ env.scrapy_all_settings.append(
+ {
+ "docname": env.docname,
+ "setting_name": setting_name,
+ "refid": refid,
+ }
+ )
def make_setting_element(setting_data, app, fromdocname):
- refnode = make_refnode(app.builder, fromdocname,
- todocname=setting_data['docname'],
- targetid=setting_data['refid'],
- child=nodes.Text(setting_data['setting_name']))
+ refnode = make_refnode(
+ app.builder,
+ fromdocname,
+ todocname=setting_data["docname"],
+ targetid=setting_data["refid"],
+ child=nodes.Text(setting_data["setting_name"]),
+ )
p = nodes.paragraph()
p += refnode
@@ -71,69 +77,72 @@ def replace_settingslist_nodes(app, doctree, fromdocname):
for node in doctree.traverse(settingslist_node):
settings_list = nodes.bullet_list()
- settings_list.extend([make_setting_element(d, app, fromdocname)
- for d in sorted(env.scrapy_all_settings,
- key=itemgetter('setting_name'))
- if fromdocname != d['docname']])
+ settings_list.extend(
+ [
+ make_setting_element(d, app, fromdocname)
+ for d in sorted(env.scrapy_all_settings, key=itemgetter("setting_name"))
+ if fromdocname != d["docname"]
+ ]
+ )
node.replace_self(settings_list)
def setup(app):
app.add_crossref_type(
- directivename = "setting",
- rolename = "setting",
- indextemplate = "pair: %s; setting",
+ directivename="setting",
+ rolename="setting",
+ indextemplate="pair: %s; setting",
)
app.add_crossref_type(
- directivename = "signal",
- rolename = "signal",
- indextemplate = "pair: %s; signal",
+ directivename="signal",
+ rolename="signal",
+ indextemplate="pair: %s; signal",
)
app.add_crossref_type(
- directivename = "command",
- rolename = "command",
- indextemplate = "pair: %s; command",
+ directivename="command",
+ rolename="command",
+ indextemplate="pair: %s; command",
)
app.add_crossref_type(
- directivename = "reqmeta",
- rolename = "reqmeta",
- indextemplate = "pair: %s; reqmeta",
+ directivename="reqmeta",
+ rolename="reqmeta",
+ indextemplate="pair: %s; reqmeta",
)
- app.add_role('source', source_role)
- app.add_role('commit', commit_role)
- app.add_role('issue', issue_role)
- app.add_role('rev', rev_role)
+ app.add_role("source", source_role)
+ app.add_role("commit", commit_role)
+ app.add_role("issue", issue_role)
+ app.add_role("rev", rev_role)
app.add_node(settingslist_node)
- app.add_directive('settingslist', SettingsListDirective)
+ app.add_directive("settingslist", SettingsListDirective)
- app.connect('doctree-read', collect_scrapy_settings_refs)
- app.connect('doctree-resolved', replace_settingslist_nodes)
+ app.connect("doctree-read", collect_scrapy_settings_refs)
+ app.connect("doctree-resolved", replace_settingslist_nodes)
def source_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
- ref = 'https://github.com/scrapy/scrapy/blob/master/' + text
+ ref = "https://github.com/scrapy/scrapy/blob/master/" + text
set_classes(options)
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], []
def issue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
- ref = 'https://github.com/scrapy/scrapy/issues/' + text
+ ref = "https://github.com/scrapy/scrapy/issues/" + text
set_classes(options)
- node = nodes.reference(rawtext, 'issue ' + text, refuri=ref, **options)
+ node = nodes.reference(rawtext, "issue " + text, refuri=ref, **options)
return [node], []
def commit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
- ref = 'https://github.com/scrapy/scrapy/commit/' + text
+ ref = "https://github.com/scrapy/scrapy/commit/" + text
set_classes(options)
- node = nodes.reference(rawtext, 'commit ' + text, refuri=ref, **options)
+ node = nodes.reference(rawtext, "commit " + text, refuri=ref, **options)
return [node], []
def rev_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
- ref = 'http://hg.scrapy.org/scrapy/changeset/' + text
+ ref = "http://hg.scrapy.org/scrapy/changeset/" + text
set_classes(options)
- node = nodes.reference(rawtext, 'r' + text, refuri=ref, **options)
+ node = nodes.reference(rawtext, "r" + text, refuri=ref, **options)
return [node], []
diff --git a/docs/_static/custom.css b/docs/_static/custom.css
new file mode 100644
index 000000000..64f16939c
--- /dev/null
+++ b/docs/_static/custom.css
@@ -0,0 +1,10 @@
+/* Move lists closer to their introducing paragraph */
+.rst-content .section ol p, .rst-content .section ul p {
+ margin-bottom: 0px;
+}
+.rst-content p + ol, .rst-content p + ul {
+ margin-top: -18px; /* Compensates margin-top: 24px of p */
+}
+.rst-content dl p + ol, .rst-content dl p + ul {
+ margin-top: -6px; /* Compensates margin-top: 12px of p */
+}
\ No newline at end of file
diff --git a/docs/_static/selectors-sample1.html b/docs/_static/selectors-sample1.html
index 8a79a3381..915718832 100644
--- a/docs/_static/selectors-sample1.html
+++ b/docs/_static/selectors-sample1.html
@@ -1,16 +1,17 @@
-
-
-
- Example website
-
-
-
-
-
+
+
+
+
+ Example website
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html
deleted file mode 100644
index a6f6cbda8..000000000
--- a/docs/_templates/layout.html
+++ /dev/null
@@ -1,16 +0,0 @@
-{% extends "!layout.html" %}
-
-{% block footer %}
-{{ super() }}
-
-{% endblock %}
diff --git a/docs/_tests/quotes.html b/docs/_tests/quotes.html
index 71aff8847..f4002ecd1 100644
--- a/docs/_tests/quotes.html
+++ b/docs/_tests/quotes.html
@@ -273,7 +273,7 @@
Quotes by: GoodReads.com
- Made with ❤ by Scrapinghub
+ Made with ❤ by Zyte
diff --git a/docs/_tests/quotes1.html b/docs/_tests/quotes1.html
index 71aff8847..f4002ecd1 100644
--- a/docs/_tests/quotes1.html
+++ b/docs/_tests/quotes1.html
@@ -273,7 +273,7 @@
Quotes by: GoodReads.com
- Made with ❤ by Scrapinghub
+ Made with ❤ by Zyte
diff --git a/docs/conf.py b/docs/conf.py
index 27d2b5dff..9ca0f817a 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -11,13 +11,12 @@
import sys
from datetime import datetime
-from os import path
+from pathlib import Path
# If your extensions are in another directory, add it here. If the directory
-# is relative to the documentation root, use os.path.abspath to make it
-# absolute, like shown here.
-sys.path.append(path.join(path.dirname(__file__), "_ext"))
-sys.path.insert(0, path.dirname(path.dirname(__file__)))
+# is relative to the documentation root, use Path.absolute to make it absolute.
+sys.path.append(str(Path(__file__).parent / "_ext"))
+sys.path.insert(0, str(Path(__file__).parent.parent))
# General configuration
@@ -26,30 +25,30 @@ sys.path.insert(0, path.dirname(path.dirname(__file__)))
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
- 'hoverxref.extension',
- 'notfound.extension',
- 'scrapydocs',
- 'sphinx.ext.autodoc',
- 'sphinx.ext.coverage',
- 'sphinx.ext.intersphinx',
- 'sphinx.ext.viewcode',
+ "hoverxref.extension",
+ "notfound.extension",
+ "scrapydocs",
+ "sphinx.ext.autodoc",
+ "sphinx.ext.coverage",
+ "sphinx.ext.intersphinx",
+ "sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
# The suffix of source filenames.
-source_suffix = '.rst'
+source_suffix = ".rst"
# The encoding of source files.
-#source_encoding = 'utf-8'
+# source_encoding = 'utf-8'
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# General information about the project.
-project = 'Scrapy'
-copyright = f'2008–{datetime.now().year}, Scrapy developers'
+project = "Scrapy"
+copyright = f"2008–{datetime.now().year}, Scrapy 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
@@ -58,50 +57,51 @@ copyright = f'2008–{datetime.now().year}, Scrapy developers'
# The short X.Y version.
try:
import scrapy
- version = '.'.join(map(str, scrapy.version_info[:2]))
+
+ version = ".".join(map(str, scrapy.version_info[:2]))
release = scrapy.__version__
except ImportError:
- version = ''
- release = ''
+ version = ""
+ release = ""
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
-language = 'en'
+language = "en"
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
-#today = ''
+# today = ''
# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
+# today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
-#unused_docs = []
+# unused_docs = []
-exclude_patterns = ['build']
+exclude_patterns = ["build"]
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
-exclude_trees = ['.build']
+exclude_trees = [".build"]
# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
+# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
+# 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
+# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
-#show_authors = False
+# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
+pygments_style = "sphinx"
# List of Sphinx warnings that will not be raised
-suppress_warnings = ['epub.unknown_project_files']
+suppress_warnings = ["epub.unknown_project_files"]
# Options for HTML output
@@ -109,19 +109,19 @@ suppress_warnings = ['epub.unknown_project_files']
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
-html_theme = 'sphinx_rtd_theme'
+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 = {}
+# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# Add path to the RTD explicitly to robustify builds (otherwise might
# fail in a clean Debian build env)
import sphinx_rtd_theme
-html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
+html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
@@ -130,44 +130,44 @@ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-#html_title = None
+# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
+# 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
+# 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
+# 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 = ['_static']
+html_static_path = ["_static"]
# 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'
+html_last_updated_fmt = "%b %d, %Y"
# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
+# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
-#html_additional_pages = {}
+# html_additional_pages = {}
# If false, no module index is generated.
-#html_use_modindex = True
+# html_use_modindex = True
# If false, no index is generated.
-#html_use_index = True
+# html_use_index = True
# If true, the index is split into individual pages for each letter.
-#html_split_index = False
+# html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/.
html_copy_source = True
@@ -175,47 +175,50 @@ html_copy_source = 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 = ''
+# html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
+# html_file_suffix = ''
# Output file base name for HTML help builder.
-htmlhelp_basename = 'Scrapydoc'
+htmlhelp_basename = "Scrapydoc"
+
+html_css_files = [
+ "custom.css",
+]
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
+# latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
+# latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
- ('index', 'Scrapy.tex', 'Scrapy Documentation',
- 'Scrapy developers', 'manual'),
+ ("index", "Scrapy.tex", "Scrapy Documentation", "Scrapy developers", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
-#latex_logo = None
+# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
-#latex_use_parts = False
+# latex_use_parts = False
# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
+# latex_preamble = ''
# Documents to append as an appendix to all manuals.
-#latex_appendices = []
+# latex_appendices = []
# If false, no module index is generated.
-#latex_use_modindex = True
+# latex_use_modindex = True
# Options for the linkcheck builder
@@ -224,8 +227,9 @@ latex_documents = [
# A list of regular expressions that match URIs that should not be checked when
# doing a linkcheck build.
linkcheck_ignore = [
- 'http://localhost:\d+', 'http://hg.scrapy.org',
- 'http://directory.google.com/'
+ "http://localhost:\d+",
+ "http://hg.scrapy.org",
+ "http://directory.google.com/",
]
@@ -235,45 +239,35 @@ coverage_ignore_pyobjects = [
# Contract’s add_pre_hook and add_post_hook are not documented because
# they should be transparent to contract developers, for whom pre_hook and
# post_hook should be the actual concern.
- r'\bContract\.add_(pre|post)_hook$',
-
+ r"\bContract\.add_(pre|post)_hook$",
# ContractsManager is an internal class, developers are not expected to
# interact with it directly in any way.
- r'\bContractsManager\b$',
-
+ r"\bContractsManager\b$",
# For default contracts we only want to document their general purpose in
# their __init__ method, the methods they reimplement to achieve that purpose
# should be irrelevant to developers using those contracts.
- r'\w+Contract\.(adjust_request_args|(pre|post)_process)$',
-
+ r"\w+Contract\.(adjust_request_args|(pre|post)_process)$",
# Methods of downloader middlewares are not documented, only the classes
# themselves, since downloader middlewares are controlled through Scrapy
# settings.
- r'^scrapy\.downloadermiddlewares\.\w*?\.(\w*?Middleware|DownloaderStats)\.',
-
+ r"^scrapy\.downloadermiddlewares\.\w*?\.(\w*?Middleware|DownloaderStats)\.",
# Base classes of downloader middlewares are implementation details that
# are not meant for users.
- r'^scrapy\.downloadermiddlewares\.\w*?\.Base\w*?Middleware',
-
+ r"^scrapy\.downloadermiddlewares\.\w*?\.Base\w*?Middleware",
# Private exception used by the command-line interface implementation.
- r'^scrapy\.exceptions\.UsageError',
-
+ r"^scrapy\.exceptions\.UsageError",
# Methods of BaseItemExporter subclasses are only documented in
# BaseItemExporter.
- r'^scrapy\.exporters\.(?!BaseItemExporter\b)\w*?\.',
-
+ r"^scrapy\.exporters\.(?!BaseItemExporter\b)\w*?\.",
# Extension behavior is only modified through settings. Methods of
# extension classes, as well as helper functions, are implementation
# details that are not documented.
- r'^scrapy\.extensions\.[a-z]\w*?\.[A-Z]\w*?\.', # methods
- r'^scrapy\.extensions\.[a-z]\w*?\.[a-z]', # helper functions
-
+ r"^scrapy\.extensions\.[a-z]\w*?\.[A-Z]\w*?\.", # methods
+ r"^scrapy\.extensions\.[a-z]\w*?\.[a-z]", # helper functions
# Never documented before, and deprecated now.
- r'^scrapy\.item\.DictItem$',
- r'^scrapy\.linkextractors\.FilteringLinkExtractor$',
-
+ r"^scrapy\.linkextractors\.FilteringLinkExtractor$",
# Implementation detail of LxmlLinkExtractor
- r'^scrapy\.linkextractors\.lxmlhtml\.LxmlParserLinkExtractor',
+ r"^scrapy\.linkextractors\.lxmlhtml\.LxmlParserLinkExtractor",
]
@@ -281,17 +275,20 @@ coverage_ignore_pyobjects = [
# -------------------------------------
intersphinx_mapping = {
- 'attrs': ('https://www.attrs.org/en/stable/', None),
- 'coverage': ('https://coverage.readthedocs.io/en/stable', None),
- 'cssselect': ('https://cssselect.readthedocs.io/en/latest', None),
- 'itemloaders': ('https://itemloaders.readthedocs.io/en/latest/', None),
- 'pytest': ('https://docs.pytest.org/en/latest', None),
- 'python': ('https://docs.python.org/3', None),
- 'sphinx': ('https://www.sphinx-doc.org/en/master', None),
- 'tox': ('https://tox.readthedocs.io/en/latest', None),
- 'twisted': ('https://twistedmatrix.com/documents/current', None),
- 'twistedapi': ('https://twistedmatrix.com/documents/current/api', None),
+ "attrs": ("https://www.attrs.org/en/stable/", None),
+ "coverage": ("https://coverage.readthedocs.io/en/latest", None),
+ "cryptography": ("https://cryptography.io/en/latest/", None),
+ "cssselect": ("https://cssselect.readthedocs.io/en/latest", None),
+ "itemloaders": ("https://itemloaders.readthedocs.io/en/latest/", None),
+ "pytest": ("https://docs.pytest.org/en/latest", None),
+ "python": ("https://docs.python.org/3", None),
+ "sphinx": ("https://www.sphinx-doc.org/en/master", None),
+ "tox": ("https://tox.wiki/en/latest/", None),
+ "twisted": ("https://docs.twisted.org/en/stable/", None),
+ "twistedapi": ("https://docs.twisted.org/en/stable/api/", None),
+ "w3lib": ("https://w3lib.readthedocs.io/en/latest", None),
}
+intersphinx_disabled_reftypes = []
# Options for sphinx-hoverxref options
@@ -300,21 +297,25 @@ intersphinx_mapping = {
hoverxref_auto_ref = True
hoverxref_role_types = {
"class": "tooltip",
+ "command": "tooltip",
"confval": "tooltip",
"hoverxref": "tooltip",
"mod": "tooltip",
"ref": "tooltip",
+ "reqmeta": "tooltip",
+ "setting": "tooltip",
+ "signal": "tooltip",
}
-hoverxref_roles = ['command', 'reqmeta', 'setting', 'signal']
+hoverxref_roles = ["command", "reqmeta", "setting", "signal"]
def setup(app):
- app.connect('autodoc-skip-member', maybe_skip_member)
+ app.connect("autodoc-skip-member", maybe_skip_member)
def maybe_skip_member(app, what, name, obj, skip, options):
if not skip:
# autodocs was generating a text "alias of" for the following members
# https://github.com/sphinx-doc/sphinx/issues/4422
- return name in {'default_item_class', 'default_selector_class'}
+ return name in {"default_item_class", "default_selector_class"}
return skip
diff --git a/docs/conftest.py b/docs/conftest.py
index 8c735e838..32f849a36 100644
--- a/docs/conftest.py
+++ b/docs/conftest.py
@@ -1,29 +1,34 @@
-import os
from doctest import ELLIPSIS, NORMALIZE_WHITESPACE
+from pathlib import Path
-from scrapy.http.response.html import HtmlResponse
from sybil import Sybil
-from sybil.parsers.codeblock import CodeBlockParser
from sybil.parsers.doctest import DocTestParser
from sybil.parsers.skip import skip
+try:
+ # >2.0.1
+ from sybil.parsers.codeblock import PythonCodeBlockParser
+except ImportError:
+ from sybil.parsers.codeblock import CodeBlockParser as PythonCodeBlockParser
-def load_response(url, filename):
- input_path = os.path.join(os.path.dirname(__file__), '_tests', filename)
- with open(input_path, 'rb') as input_file:
- return HtmlResponse(url, body=input_file.read())
+from scrapy.http.response.html import HtmlResponse
+
+
+def load_response(url: str, filename: str) -> HtmlResponse:
+ input_path = Path(__file__).parent / "_tests" / filename
+ return HtmlResponse(url, body=input_path.read_bytes())
def setup(namespace):
- namespace['load_response'] = load_response
+ namespace["load_response"] = load_response
pytest_collect_file = Sybil(
parsers=[
DocTestParser(optionflags=ELLIPSIS | NORMALIZE_WHITESPACE),
- CodeBlockParser(future_imports=['print_function']),
+ PythonCodeBlockParser(future_imports=["print_function"]),
skip,
],
- pattern='*.rst',
+ pattern="*.rst",
setup=setup,
).pytest()
diff --git a/docs/contributing.rst b/docs/contributing.rst
index 4d2580a6c..2b3249601 100644
--- a/docs/contributing.rst
+++ b/docs/contributing.rst
@@ -11,10 +11,6 @@ Contributing to Scrapy
There are many ways to contribute to Scrapy. Here are some of them:
-* Blog about Scrapy. Tell the world how you're using Scrapy. This will help
- newcomers with more examples and will help the Scrapy project to increase its
- visibility.
-
* Report bugs and request features in the `issue tracker`_, trying to follow
the guidelines detailed in `Reporting bugs`_ below.
@@ -22,13 +18,16 @@ There are many ways to contribute to Scrapy. Here are some of them:
:ref:`writing-patches` and `Submitting patches`_ below for details on how to
write and submit a patch.
+* Blog about Scrapy. Tell the world how you're using Scrapy. This will help
+ newcomers with more examples and will help the Scrapy project to increase its
+ visibility.
+
* Join the `Scrapy subreddit`_ and share your ideas on how to
improve Scrapy. We're always open to suggestions.
* Answer Scrapy questions at
`Stack Overflow `__.
-
Reporting bugs
==============
@@ -49,7 +48,7 @@ guidelines when you're going to report a new bug.
(use "scrapy" tag).
* check the `open issues`_ to see if the issue has already been reported. If it
- has, don't dismiss the report, but check the ticket history and comments. If
+ has, don't dismiss the report, but check the ticket history and comments. If
you have additional useful information, please leave a comment, or consider
:ref:`sending a pull request ` with a fix.
@@ -80,6 +79,13 @@ guidelines when you're going to report a new bug.
Writing patches
===============
+Scrapy has a list of `good first issues`_ and `help wanted issues`_ that you
+can work on. These issues are a great way to get started with contributing to
+Scrapy. If you're new to the codebase, you may want to focus on documentation
+or testing-related issues, as they are always useful and can help you get
+more familiar with the project. You can also check Scrapy's `test coverage`_
+to see which areas may benefit from more tests.
+
The better a patch is written, the higher the chances that it'll get accepted and the sooner it will be merged.
Well-written patches should:
@@ -169,16 +175,43 @@ Coding style
Please follow these coding conventions when writing code for inclusion in
Scrapy:
-* Unless otherwise specified, follow :pep:`8`.
-
-* It's OK to use lines longer than 79 chars if it improves the code
- readability.
+* We use `black `_ for code formatting.
+ There is a hook in the pre-commit config
+ that will automatically format your code before every commit. You can also
+ run black manually with ``tox -e black``.
* Don't put your name in the code you contribute; git provides enough
metadata to identify author of the code.
See https://help.github.com/en/github/using-git/setting-your-username-in-git for
setup instructions.
+.. _scrapy-pre-commit:
+
+Pre-commit
+==========
+
+We use `pre-commit`_ to automatically address simple code issues before every
+commit.
+
+.. _pre-commit: https://pre-commit.com/
+
+After your create a local clone of your fork of the Scrapy repository:
+
+#. `Install pre-commit `_.
+
+#. On the root of your local clone of the Scrapy repository, run the following
+ command:
+
+ .. code-block:: bash
+
+ pre-commit install
+
+Now pre-commit will check your changes every time you create a Git commit. Upon
+finding issues, pre-commit aborts your commit, and either fixes those issues
+automatically, or only reports them to you. If it fixes those issues
+automatically, creating your commit again should succeed. Otherwise, you may
+need to address the corresponding issues manually first.
+
.. _documentation-policies:
Documentation policies
@@ -214,7 +247,7 @@ Tests
=====
Tests are implemented using the :doc:`Twisted unit-testing framework
-`. Running tests requires
+`. Running tests requires
:doc:`tox `.
.. _running-tests:
@@ -232,15 +265,15 @@ To run a specific test (say ``tests/test_loader.py``) use:
To run the tests on a specific :doc:`tox ` environment, use
``-e `` with an environment name from ``tox.ini``. For example, to run
-the tests with Python 3.6 use::
+the tests with Python 3.10 use::
- tox -e py36
+ tox -e py310
You can also specify a comma-separated list of environments, and use :ref:`tox’s
parallel mode ` to run the tests on multiple environments in
parallel::
- tox -e py36,py38 -p auto
+ tox -e py39,py310 -p auto
To pass command-line options to :doc:`pytest `, add them after
``--`` in your call to :doc:`tox `. Using ``--`` overrides the
@@ -250,9 +283,9 @@ default positional arguments (``scrapy tests``) after ``--`` as well::
tox -- scrapy tests -x # stop after first failure
You can also use the `pytest-xdist`_ plugin. For example, to run all tests on
-the Python 3.6 :doc:`tox ` environment using all your CPU cores::
+the Python 3.10 :doc:`tox ` environment using all your CPU cores::
- tox -e py36 -- scrapy tests -n auto
+ tox -e py310 -- scrapy tests -n auto
To see coverage report install :doc:`coverage `
(``pip install coverage``) and run:
@@ -287,3 +320,6 @@ And their unit-tests are in::
.. _PEP 257: https://www.python.org/dev/peps/pep-0257/
.. _pull request: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request
.. _pytest-xdist: https://github.com/pytest-dev/pytest-xdist
+.. _good first issues: https://github.com/scrapy/scrapy/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22
+.. _help wanted issues: https://github.com/scrapy/scrapy/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22
+.. _test coverage: https://app.codecov.io/gh/scrapy/scrapy
diff --git a/docs/faq.rst b/docs/faq.rst
index 9346ec358..20dd814df 100644
--- a/docs/faq.rst
+++ b/docs/faq.rst
@@ -35,8 +35,10 @@ for parsing HTML responses in Scrapy callbacks.
You just have to feed the response's body into a ``BeautifulSoup`` object
and extract whatever data you need from it.
-Here's an example spider using BeautifulSoup API, with ``lxml`` as the HTML parser::
+Here's an example spider using BeautifulSoup API, with ``lxml`` as the HTML parser:
+.. skip: next
+.. code-block:: python
from bs4 import BeautifulSoup
import scrapy
@@ -45,17 +47,12 @@ Here's an example spider using BeautifulSoup API, with ``lxml`` as the HTML pars
class ExampleSpider(scrapy.Spider):
name = "example"
allowed_domains = ["example.com"]
- start_urls = (
- 'http://www.example.com/',
- )
+ start_urls = ("http://www.example.com/",)
def parse(self, response):
# use lxml to get decent HTML parsing speed
- soup = BeautifulSoup(response.text, 'lxml')
- yield {
- "url": response.url,
- "title": soup.h1.string
- }
+ soup = BeautifulSoup(response.text, "lxml")
+ yield {"url": response.url, "title": soup.h1.string}
.. note::
@@ -94,15 +91,6 @@ How can I scrape an item with attributes in different pages?
See :ref:`topics-request-response-ref-request-callback-arguments`.
-
-Scrapy crashes with: ImportError: No module named win32api
-----------------------------------------------------------
-
-You need to install `pywin32`_ because of `this Twisted bug`_.
-
-.. _pywin32: https://sourceforge.net/projects/pywin32/
-.. _this Twisted bug: https://twistedmatrix.com/trac/ticket/3707
-
How can I simulate a user login in my spider?
---------------------------------------------
@@ -118,11 +106,13 @@ basically means that it crawls in `DFO order`_. This order is more convenient
in most cases.
If you do want to crawl in true `BFO order`_, you can do it by
-setting the following settings::
+setting the following settings:
+
+.. code-block:: python
DEPTH_PRIORITY = 1
- SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
- SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'
+ SCHEDULER_DISK_QUEUE = "scrapy.squeues.PickleFifoDiskQueue"
+ SCHEDULER_MEMORY_QUEUE = "scrapy.squeues.FifoMemoryQueue"
While pending requests are below the configured values of
:setting:`CONCURRENT_REQUESTS`, :setting:`CONCURRENT_REQUESTS_PER_DOMAIN` or
@@ -145,6 +135,43 @@ How can I make Scrapy consume less memory?
See previous question.
+How can I prevent memory errors due to many allowed domains?
+------------------------------------------------------------
+
+If you have a spider with a long list of
+:attr:`~scrapy.Spider.allowed_domains` (e.g. 50,000+), consider
+replacing the default
+:class:`~scrapy.spidermiddlewares.offsite.OffsiteMiddleware` spider middleware
+with a :ref:`custom spider middleware ` that requires
+less memory. For example:
+
+- If your domain names are similar enough, use your own regular expression
+ instead joining the strings in
+ :attr:`~scrapy.Spider.allowed_domains` into a complex regular
+ expression.
+
+- If you can `meet the installation requirements`_, use pyre2_ instead of
+ Python’s re_ to compile your URL-filtering regular expression. See
+ :issue:`1908`.
+
+See also other suggestions at `StackOverflow`_.
+
+.. note:: Remember to disable
+ :class:`scrapy.spidermiddlewares.offsite.OffsiteMiddleware` when you enable
+ your custom implementation:
+
+ .. code-block:: python
+
+ SPIDER_MIDDLEWARES = {
+ "scrapy.spidermiddlewares.offsite.OffsiteMiddleware": None,
+ "myproject.middlewares.CustomOffsiteMiddleware": 500,
+ }
+
+.. _meet the installation requirements: https://github.com/andreasvc/pyre2#installation
+.. _pyre2: https://github.com/andreasvc/pyre2
+.. _re: https://docs.python.org/library/re.html
+.. _StackOverflow: https://stackoverflow.com/q/36440681/939364
+
Can I use Basic HTTP Authentication in my spiders?
--------------------------------------------------
@@ -204,16 +231,20 @@ Can I return (Twisted) deferreds from signal handlers?
Some signals support returning deferreds from their handlers, others don't. See
the :ref:`topics-signals-ref` to know which ones.
-What does the response status code 999 means?
----------------------------------------------
+What does the response status code 999 mean?
+--------------------------------------------
999 is a custom response status code used by Yahoo sites to throttle requests.
Try slowing down the crawling speed by using a download delay of ``2`` (or
-higher) in your spider::
+higher) in your spider:
+
+.. code-block:: python
+
+ from scrapy.spiders import CrawlSpider
+
class MySpider(CrawlSpider):
-
- name = 'myspider'
+ name = "myspider"
download_delay = 2
@@ -315,6 +346,7 @@ I'm scraping a XML document and my XPath selector doesn't return any items
You may need to remove namespaces. See :ref:`removing-namespaces`.
+
.. _faq-split-item:
How to split an item into multiple items in an item pipeline?
@@ -324,19 +356,21 @@ How to split an item into multiple items in an item pipeline?
input item. :ref:`Create a spider middleware `
instead, and use its
:meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output`
-method for this purpose. For example::
+method for this purpose. For example:
+
+.. code-block:: python
from copy import deepcopy
from itemadapter import is_item, ItemAdapter
- class MultiplyItemsMiddleware:
+ class MultiplyItemsMiddleware:
def process_spider_output(self, response, result, spider):
for item in result:
if is_item(item):
adapter = ItemAdapter(item)
- for _ in range(adapter['multiply_by']):
+ for _ in range(adapter["multiply_by"]):
yield deepcopy(item)
Does Scrapy support IPv6 addresses?
@@ -363,14 +397,26 @@ How can I cancel the download of a given response?
--------------------------------------------------
In some situations, it might be useful to stop the download of a certain response.
-For instance, if you only need the first part of a large response and you would like
-to save resources by avoiding the download of the whole body.
-In that case, you could attach a handler to the :class:`~scrapy.signals.bytes_received`
-signal and raise a :exc:`~scrapy.exceptions.StopDownload` exception. Please refer to
-the :ref:`topics-stop-response-download` topic for additional information and examples.
+For instance, sometimes you can determine whether or not you need the full contents
+of a response by inspecting its headers or the first bytes of its body. In that case,
+you could save resources by attaching a handler to the :class:`~scrapy.signals.bytes_received`
+or :class:`~scrapy.signals.headers_received` signals and raising a
+:exc:`~scrapy.exceptions.StopDownload` exception. Please refer to the
+:ref:`topics-stop-response-download` topic for additional information and examples.
+
+
+Running ``runspider`` I get ``error: No spider found in file: ``
+--------------------------------------------------------------------------
+
+This may happen if your Scrapy project has a spider module with a name that
+conflicts with the name of one of the `Python standard library modules`_, such
+as ``csv.py`` or ``os.py``, or any `Python package`_ that you have installed.
+See :issue:`2680`.
.. _has been reported: https://github.com/scrapy/scrapy/issues/2905
+.. _Python standard library modules: https://docs.python.org/py-modindex.html
+.. _Python package: https://pypi.org/
.. _user agents: https://en.wikipedia.org/wiki/User_agent
.. _LIFO: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
.. _DFO order: https://en.wikipedia.org/wiki/Depth-first_search
diff --git a/docs/index.rst b/docs/index.rst
index da264fb34..8798aebd1 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -12,6 +12,8 @@ testing.
.. _web crawling: https://en.wikipedia.org/wiki/Web_crawler
.. _web scraping: https://en.wikipedia.org/wiki/Web_scraping
+.. _getting-help:
+
Getting help
============
@@ -24,12 +26,14 @@ Having trouble? We'd like to help!
* Search for questions on the archives of the `scrapy-users mailing list`_.
* Ask a question in the `#scrapy IRC channel`_,
* Report bugs with Scrapy in our `issue tracker`_.
+* Join the Discord community `Scrapy Discord`_.
.. _scrapy-users mailing list: https://groups.google.com/forum/#!forum/scrapy-users
.. _Scrapy subreddit: https://www.reddit.com/r/scrapy/
.. _StackOverflow using the scrapy tag: https://stackoverflow.com/tags/scrapy
.. _#scrapy IRC channel: irc://irc.freenode.net/scrapy
.. _issue tracker: https://github.com/scrapy/scrapy/issues
+.. _Scrapy Discord: https://discord.gg/mv3yErfpvq
First steps
@@ -126,7 +130,6 @@ Built-in services
topics/stats
topics/email
topics/telnetconsole
- topics/webservice
:doc:`topics/logging`
Learn how to use Python's builtin logging on Scrapy.
@@ -140,9 +143,6 @@ Built-in services
:doc:`topics/telnetconsole`
Inspect a running crawler using a built-in Python console.
-:doc:`topics/webservice`
- Monitor and control a crawler using a web service.
-
Solving specific problems
=========================
@@ -222,17 +222,23 @@ Extending Scrapy
:hidden:
topics/architecture
+ topics/addons
topics/downloader-middleware
topics/spider-middleware
topics/extensions
- topics/api
topics/signals
+ topics/scheduler
topics/exporters
+ topics/components
+ topics/api
:doc:`topics/architecture`
Understand the Scrapy architecture.
+:doc:`topics/addons`
+ Enable and configure third-party extensions.
+
:doc:`topics/downloader-middleware`
Customize how pages get requested and downloaded.
@@ -242,15 +248,22 @@ Extending Scrapy
:doc:`topics/extensions`
Extend Scrapy with your custom functionality
-:doc:`topics/api`
- Use it on extensions and middlewares to extend Scrapy functionality
-
:doc:`topics/signals`
See all available signals and how to work with them.
+:doc:`topics/scheduler`
+ Understand the scheduler component.
+
:doc:`topics/exporters`
Quickly export your scraped items to a file (XML, CSV, etc).
+:doc:`topics/components`
+ Learn the common API and some good practices when building custom Scrapy
+ components.
+
+:doc:`topics/api`
+ Use it on extensions and middlewares to extend Scrapy functionality.
+
All the rest
============
diff --git a/docs/intro/examples.rst b/docs/intro/examples.rst
index 96363c7d5..edff894c6 100644
--- a/docs/intro/examples.rst
+++ b/docs/intro/examples.rst
@@ -7,7 +7,7 @@ Examples
The best way to learn is with examples, and Scrapy is no exception. For this
reason, there is an example Scrapy project named quotesbot_, that you can use to
play and learn more about Scrapy. It contains two spiders for
-http://quotes.toscrape.com, one using CSS selectors and another one using XPath
+https://quotes.toscrape.com, one using CSS selectors and another one using XPath
expressions.
The quotesbot_ project is available at: https://github.com/scrapy/quotesbot.
diff --git a/docs/intro/install.rst b/docs/intro/install.rst
index 3bfd3bc3b..c90c1d2bf 100644
--- a/docs/intro/install.rst
+++ b/docs/intro/install.rst
@@ -9,9 +9,10 @@ Installation guide
Supported Python versions
=========================
-Scrapy requires Python 3.6+, either the CPython implementation (default) or
-the PyPy 7.2.0+ implementation (see :ref:`python:implementations`).
+Scrapy requires Python 3.8+, either the CPython implementation (default) or
+the PyPy implementation (see :ref:`python:implementations`).
+.. _intro-install-scrapy:
Installing Scrapy
=================
@@ -29,13 +30,13 @@ you can install Scrapy and its dependencies from PyPI with::
pip install Scrapy
+We strongly recommend that you install Scrapy in :ref:`a dedicated virtualenv `,
+to avoid conflicting with your system packages.
+
Note that sometimes this may require solving compilation issues for some Scrapy
dependencies depending on your operating system, so be sure to check the
:ref:`intro-install-platform-notes`.
-We strongly recommend that you install Scrapy in :ref:`a dedicated virtualenv `,
-to avoid conflicting with your system packages.
-
For more detailed and platform specifics instructions, as well as
troubleshooting information, read on.
@@ -51,17 +52,7 @@ Scrapy is written in pure Python and depends on a few key Python packages (among
* `twisted`_, an asynchronous networking framework
* `cryptography`_ and `pyOpenSSL`_, to deal with various network-level security needs
-The minimal versions which Scrapy is tested against are:
-
-* Twisted 14.0
-* lxml 3.4
-* pyOpenSSL 0.14
-
-Scrapy may work with older versions of these packages
-but it is not guaranteed it will continue working
-because it’s not being tested against them.
-
-Some of these packages themselves depends on non-Python packages
+Some of these packages themselves depend on non-Python packages
that might require additional installation steps depending on your platform.
Please check :ref:`platform-specific guides below `.
@@ -69,10 +60,9 @@ In case of any trouble related to these dependencies,
please refer to their respective installation instructions:
* `lxml installation`_
-* `cryptography installation`_
+* :doc:`cryptography installation `
.. _lxml installation: https://lxml.de/installation.html
-.. _cryptography installation: https://cryptography.io/en/latest/installation/
.. _intro-using-virtualenv:
@@ -118,6 +108,27 @@ Once you've installed `Anaconda`_ or `Miniconda`_, install Scrapy with::
conda install -c conda-forge scrapy
+To install Scrapy on Windows using ``pip``:
+
+.. warning::
+ This installation method requires “Microsoft Visual C++” for installing some
+ Scrapy dependencies, which demands significantly more disk space than Anaconda.
+
+#. Download and execute `Microsoft C++ Build Tools`_ to install the Visual Studio Installer.
+
+#. Run the Visual Studio Installer.
+
+#. Under the Workloads section, select **C++ build tools**.
+
+#. Check the installation details and make sure following packages are selected as optional components:
+
+ * **MSVC** (e.g MSVC v142 - VS 2019 C++ x64/x86 build tools (v14.23) )
+
+ * **Windows SDK** (e.g Windows 10 SDK (10.0.18362.0))
+
+#. Install the Visual Studio Build Tools.
+
+Now, you should be able to :ref:`install Scrapy ` using ``pip``.
.. _intro-install-ubuntu:
@@ -169,14 +180,14 @@ prevents ``pip`` from updating system packages. This has to be addressed to
successfully install Scrapy and its dependencies. Here are some proposed
solutions:
-* *(Recommended)* **Don't** use system python, install a new, updated version
+* *(Recommended)* **Don't** use system Python. Install a new, updated version
that doesn't conflict with the rest of your system. Here's how to do it using
the `homebrew`_ package manager:
* Install `homebrew`_ following the instructions in https://brew.sh/
* Update your ``PATH`` variable to state that homebrew packages should be
- used before system packages (Change ``.bashrc`` to ``.zshrc`` accordantly
+ used before system packages (Change ``.bashrc`` to ``.zshrc`` accordingly
if you're using `zsh`_ as default shell)::
echo "export PATH=/usr/local/bin:/usr/local/sbin:$PATH" >> ~/.bashrc
@@ -208,13 +219,13 @@ After any of these workarounds you should be able to install Scrapy::
PyPy
----
-We recommend using the latest PyPy version. The version tested is 5.9.0.
+We recommend using the latest PyPy version.
For PyPy3, only Linux installation was tested.
Most Scrapy dependencies now have binary wheels for CPython, but not for PyPy.
This means that these dependencies will be built during installation.
-On macOS, you are likely to face an issue with building Cryptography dependency,
-solution to this problem is described
+On macOS, you are likely to face an issue with building the Cryptography
+dependency. The solution to this problem is described
`here `_,
that is to ``brew install openssl`` and then export the flags that this command
recommends (only needed when installing Scrapy). Installing on Linux has no special
@@ -265,10 +276,10 @@ For details, see `Issue #2473 `_.
.. _cryptography: https://cryptography.io/en/latest/
.. _pyOpenSSL: https://pypi.org/project/pyOpenSSL/
.. _setuptools: https://pypi.python.org/pypi/setuptools
-.. _AUR Scrapy package: https://aur.archlinux.org/packages/scrapy/
.. _homebrew: https://brew.sh/
.. _zsh: https://www.zsh.org/
-.. _Scrapinghub: https://scrapinghub.com
.. _Anaconda: https://docs.anaconda.com/anaconda/
.. _Miniconda: https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html
+.. _Visual Studio: https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio
+.. _Microsoft C++ Build Tools: https://visualstudio.microsoft.com/visual-cpp-build-tools/
.. _conda-forge: https://conda-forge.org/
diff --git a/docs/intro/overview.rst b/docs/intro/overview.rst
index dd80c7bd0..542760b4f 100644
--- a/docs/intro/overview.rst
+++ b/docs/intro/overview.rst
@@ -4,7 +4,7 @@
Scrapy at a glance
==================
-Scrapy is an application framework for crawling web sites and extracting
+Scrapy (/ˈskreɪpaɪ/) is an application framework for crawling web sites and extracting
structured data which can be used for a wide range of useful applications, like
data mining, information processing or historical archival.
@@ -20,22 +20,24 @@ In order to show you what Scrapy brings to the table, we'll walk you through an
example of a Scrapy Spider using the simplest way to run a spider.
Here's the code for a spider that scrapes famous quotes from website
-http://quotes.toscrape.com, following the pagination::
+https://quotes.toscrape.com, following the pagination:
+
+.. code-block:: python
import scrapy
class QuotesSpider(scrapy.Spider):
- name = 'quotes'
+ name = "quotes"
start_urls = [
- 'http://quotes.toscrape.com/tag/humor/',
+ "https://quotes.toscrape.com/tag/humor/",
]
def parse(self, response):
- for quote in response.css('div.quote'):
+ for quote in response.css("div.quote"):
yield {
- 'author': quote.xpath('span/small/text()').get(),
- 'text': quote.css('span.text::text').get(),
+ "author": quote.xpath("span/small/text()").get(),
+ "text": quote.css("span.text::text").get(),
}
next_page = response.css('li.next a::attr("href")').get()
@@ -45,9 +47,9 @@ http://quotes.toscrape.com, following the pagination::
Put this in a text file, name it to something like ``quotes_spider.py``
and run the spider using the :command:`runspider` command::
- scrapy runspider quotes_spider.py -o quotes.jl
+ scrapy runspider quotes_spider.py -o quotes.jsonl
-When this finishes you will have in the ``quotes.jl`` file a list of the
+When this finishes you will have in the ``quotes.jsonl`` file a list of the
quotes in JSON Lines format, containing text and author, looking like this::
{"author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"}
diff --git a/docs/intro/tutorial.rst b/docs/intro/tutorial.rst
index 9270ff42c..8ea98f29b 100644
--- a/docs/intro/tutorial.rst
+++ b/docs/intro/tutorial.rst
@@ -7,7 +7,7 @@ Scrapy Tutorial
In this tutorial, we'll assume that Scrapy is already installed on your system.
If that's not the case, see :ref:`intro-install`.
-We are going to scrape `quotes.toscrape.com `_, a website
+We are going to scrape `quotes.toscrape.com `_, a website
that lists quotes from famous authors.
This tutorial will walk you through these tasks:
@@ -78,12 +78,16 @@ Our first Spider
Spiders are classes that you define and that Scrapy uses to scrape information
from a website (or a group of websites). They must subclass
-:class:`~scrapy.spiders.Spider` and define the initial requests to make,
+:class:`~scrapy.Spider` and define the initial requests to make,
optionally how to follow links in the pages, and how to parse the downloaded
page content to extract data.
This is the code for our first Spider. Save it in a file named
-``quotes_spider.py`` under the ``tutorial/spiders`` directory in your project::
+``quotes_spider.py`` under the ``tutorial/spiders`` directory in your project:
+
+.. code-block:: python
+
+ from pathlib import Path
import scrapy
@@ -93,40 +97,39 @@ This is the code for our first Spider. Save it in a file named
def start_requests(self):
urls = [
- 'http://quotes.toscrape.com/page/1/',
- 'http://quotes.toscrape.com/page/2/',
+ "https://quotes.toscrape.com/page/1/",
+ "https://quotes.toscrape.com/page/2/",
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
page = response.url.split("/")[-2]
- filename = f'quotes-{page}.html'
- with open(filename, 'wb') as f:
- f.write(response.body)
- self.log(f'Saved file {filename}')
+ filename = f"quotes-{page}.html"
+ Path(filename).write_bytes(response.body)
+ self.log(f"Saved file {filename}")
-As you can see, our Spider subclasses :class:`scrapy.Spider `
+As you can see, our Spider subclasses :class:`scrapy.Spider `
and defines some attributes and methods:
-* :attr:`~scrapy.spiders.Spider.name`: identifies the Spider. It must be
+* :attr:`~scrapy.Spider.name`: identifies the Spider. It must be
unique within a project, that is, you can't set the same name for different
Spiders.
-* :meth:`~scrapy.spiders.Spider.start_requests`: must return an iterable of
+* :meth:`~scrapy.Spider.start_requests`: must return an iterable of
Requests (you can return a list of requests or write a generator function)
which the Spider will begin to crawl from. Subsequent requests will be
generated successively from these initial requests.
-* :meth:`~scrapy.spiders.Spider.parse`: a method that will be called to handle
+* :meth:`~scrapy.Spider.parse`: a method that will be called to handle
the response downloaded for each of the requests made. The response parameter
is an instance of :class:`~scrapy.http.TextResponse` that holds
the page content and has further helpful methods to handle it.
- The :meth:`~scrapy.spiders.Spider.parse` method usually parses the response, extracting
+ The :meth:`~scrapy.Spider.parse` method usually parses the response, extracting
the scraped data as dicts and also finding new URLs to
- follow and creating new requests (:class:`~scrapy.http.Request`) from them.
+ follow and creating new requests (:class:`~scrapy.Request`) from them.
How to run our spider
---------------------
@@ -143,9 +146,9 @@ similar to this::
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Spider opened
2016-12-16 21:24:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-12-16 21:24:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
- 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) (referer: None)
- 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
- 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
+ 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) (referer: None)
+ 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
+ 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-1.html
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-2.html
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Closing spider (finished)
@@ -162,7 +165,7 @@ for the respective URLs, as our ``parse`` method instructs.
What just happened under the hood?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Scrapy schedules the :class:`scrapy.Request ` objects
+Scrapy schedules the :class:`scrapy.Request ` objects
returned by the ``start_requests`` method of the Spider. Upon receiving a
response for each one, it instantiates :class:`~scrapy.http.Response` objects
and calls the callback method associated with the request (in this case, the
@@ -171,12 +174,16 @@ and calls the callback method associated with the request (in this case, the
A shortcut to the start_requests method
---------------------------------------
-Instead of implementing a :meth:`~scrapy.spiders.Spider.start_requests` method
-that generates :class:`scrapy.Request ` objects from URLs,
-you can just define a :attr:`~scrapy.spiders.Spider.start_urls` class attribute
+Instead of implementing a :meth:`~scrapy.Spider.start_requests` method
+that generates :class:`scrapy.Request ` objects from URLs,
+you can just define a :attr:`~scrapy.Spider.start_urls` class attribute
with a list of URLs. This list will then be used by the default implementation
-of :meth:`~scrapy.spiders.Spider.start_requests` to create the initial requests
-for your spider::
+of :meth:`~scrapy.Spider.start_requests` to create the initial requests
+for your spider.
+
+.. code-block:: python
+
+ from pathlib import Path
import scrapy
@@ -184,19 +191,18 @@ for your spider::
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
- 'http://quotes.toscrape.com/page/1/',
- 'http://quotes.toscrape.com/page/2/',
+ "https://quotes.toscrape.com/page/1/",
+ "https://quotes.toscrape.com/page/2/",
]
def parse(self, response):
page = response.url.split("/")[-2]
- filename = f'quotes-{page}.html'
- with open(filename, 'wb') as f:
- f.write(response.body)
+ filename = f"quotes-{page}.html"
+ Path(filename).write_bytes(response.body)
-The :meth:`~scrapy.spiders.Spider.parse` method will be called to handle each
+The :meth:`~scrapy.Spider.parse` method will be called to handle each
of the requests for those URLs, even though we haven't explicitly told Scrapy
-to do so. This happens because :meth:`~scrapy.spiders.Spider.parse` is Scrapy's
+to do so. This happens because :meth:`~scrapy.Spider.parse` is Scrapy's
default callback method, which is called for requests without an explicitly
assigned callback.
@@ -207,7 +213,7 @@ Extracting data
The best way to learn how to extract data with Scrapy is trying selectors
using the :ref:`Scrapy shell `. Run::
- scrapy shell 'http://quotes.toscrape.com/page/1/'
+ scrapy shell 'https://quotes.toscrape.com/page/1/'
.. note::
@@ -217,18 +223,18 @@ using the :ref:`Scrapy shell `. Run::
On Windows, use double quotes instead::
- scrapy shell "http://quotes.toscrape.com/page/1/"
+ scrapy shell "https://quotes.toscrape.com/page/1/"
You will see something like::
[ ... Scrapy log here ... ]
- 2016-09-19 12:09:27 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
+ 2016-09-19 12:09:27 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler
[s] item {}
- [s] request
- [s] response <200 http://quotes.toscrape.com/page/1/>
+ [s] request
+ [s] response <200 https://quotes.toscrape.com/page/1/>
[s] settings
[s] spider
[s] Useful shortcuts:
@@ -241,45 +247,69 @@ object:
.. invisible-code-block: python
- response = load_response('http://quotes.toscrape.com/page/1/', 'quotes1.html')
+ response = load_response('https://quotes.toscrape.com/page/1/', 'quotes1.html')
->>> response.css('title')
-[]
+.. code-block:: pycon
+
+ >>> response.css("title")
+ []
The result of running ``response.css('title')`` is a list-like object called
:class:`~scrapy.selector.SelectorList`, which represents a list of
-:class:`~scrapy.selector.Selector` objects that wrap around XML/HTML elements
+:class:`~scrapy.Selector` objects that wrap around XML/HTML elements
and allow you to run further queries to fine-grain the selection or extract the
data.
To extract the text from the title above, you can do:
->>> response.css('title::text').getall()
-['Quotes to Scrape']
+.. code-block:: pycon
+
+ >>> response.css("title::text").getall()
+ ['Quotes to Scrape']
There are two things to note here: one is that we've added ``::text`` to the
CSS query, to mean we want to select only the text elements directly inside
```` element. If we don't specify ``::text``, we'd get the full title
element, including its tags:
->>> response.css('title').getall()
-['Quotes to Scrape ']
+.. code-block:: pycon
+
+ >>> response.css("title").getall()
+ ['Quotes to Scrape ']
The other thing is that the result of calling ``.getall()`` is a list: it is
possible that a selector returns more than one result, so we extract them all.
When you know you just want the first result, as in this case, you can do:
->>> response.css('title::text').get()
-'Quotes to Scrape'
+.. code-block:: pycon
+
+ >>> response.css("title::text").get()
+ 'Quotes to Scrape'
As an alternative, you could've written:
->>> response.css('title::text')[0].get()
-'Quotes to Scrape'
+.. code-block:: pycon
-However, using ``.get()`` directly on a :class:`~scrapy.selector.SelectorList`
-instance avoids an ``IndexError`` and returns ``None`` when it doesn't
-find any element matching the selection.
+ >>> response.css("title::text")[0].get()
+ 'Quotes to Scrape'
+
+Accessing an index on a :class:`~scrapy.selector.SelectorList` instance will
+raise an :exc:`IndexError` exception if there are no results:
+
+.. code-block:: pycon
+
+ >>> response.css("noelement")[0].get()
+ Traceback (most recent call last):
+ ...
+ IndexError: list index out of range
+
+You might want to use ``.get()`` directly on the
+:class:`~scrapy.selector.SelectorList` instance instead, which returns ``None``
+if there are no results:
+
+.. code-block:: pycon
+
+ >>> response.css("noelement").get()
There's a lesson here: for most scraping code, you want it to be resilient to
errors due to things not being found on a page, so that even if some parts fail
@@ -290,14 +320,16 @@ Besides the :meth:`~scrapy.selector.SelectorList.getall` and
the :meth:`~scrapy.selector.SelectorList.re` method to extract using
:doc:`regular expressions `:
->>> response.css('title::text').re(r'Quotes.*')
-['Quotes to Scrape']
->>> response.css('title::text').re(r'Q\w+')
-['Quotes']
->>> response.css('title::text').re(r'(\w+) to (\w+)')
-['Quotes', 'Scrape']
+.. code-block:: pycon
-In order to find the proper CSS selectors to use, you might find useful opening
+ >>> response.css("title::text").re(r"Quotes.*")
+ ['Quotes to Scrape']
+ >>> response.css("title::text").re(r"Q\w+")
+ ['Quotes']
+ >>> response.css("title::text").re(r"(\w+) to (\w+)")
+ ['Quotes', 'Scrape']
+
+In order to find the proper CSS selectors to use, you might find it useful to open
the response page from the shell in your web browser using ``view(response)``.
You can use your browser's developer tools to inspect the HTML and come up
with a selector (see :ref:`topics-developer-tools`).
@@ -313,10 +345,12 @@ XPath: a brief intro
Besides `CSS`_, Scrapy selectors also support using `XPath`_ expressions:
->>> response.xpath('//title')
-[]
->>> response.xpath('//title/text()').get()
-'Quotes to Scrape'
+.. code-block:: pycon
+
+ >>> response.xpath("//title")
+ []
+ >>> response.xpath("//title/text()").get()
+ 'Quotes to Scrape'
XPath expressions are very powerful, and are the foundation of Scrapy
Selectors. In fact, CSS selectors are converted to XPath under-the-hood. You
@@ -345,7 +379,7 @@ Extracting quotes and authors
Now that you know a bit about selection and extraction, let's complete our
spider by writing the code to extract the quotes from the web page.
-Each quote in http://quotes.toscrape.com is represented by HTML elements that look
+Each quote in https://quotes.toscrape.com is represented by HTML elements that look
like this:
.. code-block:: html
@@ -369,37 +403,45 @@ like this:
Let's open up scrapy shell and play a bit to find out how to extract the data
we want::
- $ scrapy shell 'http://quotes.toscrape.com'
+ scrapy shell 'https://quotes.toscrape.com'
We get a list of selectors for the quote HTML elements with:
->>> response.css("div.quote")
-[,
- ,
- ...]
+.. code-block:: pycon
+
+ >>> response.css("div.quote")
+ [,
+ ,
+ ...]
Each of the selectors returned by the query above allows us to run further
queries over their sub-elements. Let's assign the first selector to a
variable, so that we can run our CSS selectors directly on a particular quote:
->>> quote = response.css("div.quote")[0]
+.. code-block:: pycon
+
+ >>> quote = response.css("div.quote")[0]
Now, let's extract ``text``, ``author`` and the ``tags`` from that quote
using the ``quote`` object we just created:
->>> text = quote.css("span.text::text").get()
->>> text
-'“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'
->>> author = quote.css("small.author::text").get()
->>> author
-'Albert Einstein'
+.. code-block:: pycon
+
+ >>> text = quote.css("span.text::text").get()
+ >>> text
+ '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'
+ >>> author = quote.css("small.author::text").get()
+ >>> author
+ 'Albert Einstein'
Given that the tags are a list of strings, we can use the ``.getall()`` method
to get all of them:
->>> tags = quote.css("div.tags a.tag::text").getall()
->>> tags
-['change', 'deep-thoughts', 'thinking', 'world']
+.. code-block:: pycon
+
+ >>> tags = quote.css("div.tags a.tag::text").getall()
+ >>> tags
+ ['change', 'deep-thoughts', 'thinking', 'world']
.. invisible-code-block: python
@@ -408,14 +450,17 @@ to get all of them:
Having figured out how to extract each bit, we can now iterate over all the
quotes elements and put them together into a Python dictionary:
->>> for quote in response.css("div.quote"):
-... text = quote.css("span.text::text").get()
-... author = quote.css("small.author::text").get()
-... tags = quote.css("div.tags a.tag::text").getall()
-... print(dict(text=text, author=author, tags=tags))
-{'text': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'author': 'Albert Einstein', 'tags': ['change', 'deep-thoughts', 'thinking', 'world']}
-{'text': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”', 'author': 'J.K. Rowling', 'tags': ['abilities', 'choices']}
-...
+.. code-block:: pycon
+
+ >>> for quote in response.css("div.quote"):
+ ... text = quote.css("span.text::text").get()
+ ... author = quote.css("small.author::text").get()
+ ... tags = quote.css("div.tags a.tag::text").getall()
+ ... print(dict(text=text, author=author, tags=tags))
+ ...
+ {'text': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'author': 'Albert Einstein', 'tags': ['change', 'deep-thoughts', 'thinking', 'world']}
+ {'text': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”', 'author': 'J.K. Rowling', 'tags': ['abilities', 'choices']}
+ ...
Extracting data in our spider
-----------------------------
@@ -426,7 +471,9 @@ extraction logic above into our spider.
A Scrapy spider typically generates many dictionaries containing the data
extracted from the page. To do that, we use the ``yield`` Python keyword
-in the callback, as you can see below::
+in the callback, as you can see below:
+
+.. code-block:: python
import scrapy
@@ -434,23 +481,31 @@ in the callback, as you can see below::
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
- 'http://quotes.toscrape.com/page/1/',
- 'http://quotes.toscrape.com/page/2/',
+ "https://quotes.toscrape.com/page/1/",
+ "https://quotes.toscrape.com/page/2/",
]
def parse(self, response):
- for quote in response.css('div.quote'):
+ for quote in response.css("div.quote"):
yield {
- 'text': quote.css('span.text::text').get(),
- 'author': quote.css('small.author::text').get(),
- 'tags': quote.css('div.tags a.tag::text').getall(),
+ "text": quote.css("span.text::text").get(),
+ "author": quote.css("small.author::text").get(),
+ "tags": quote.css("div.tags a.tag::text").getall(),
}
-If you run this spider, it will output the extracted data with the log::
+To run this spider, exit the scrapy shell by entering::
- 2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>
+ quit()
+
+Then, run::
+
+ scrapy crawl quotes
+
+Now, it should output the extracted data with the log::
+
+ 2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 https://quotes.toscrape.com/page/1/>
{'tags': ['life', 'love'], 'author': 'André Gide', 'text': '“It is better to be hated for what you are than to be loved for what you are not.”'}
- 2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>
+ 2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 https://quotes.toscrape.com/page/1/>
{'tags': ['edison', 'failure', 'inspirational', 'paraphrased'], 'author': 'Thomas A. Edison', 'text': "“I have not failed. I've just found 10,000 ways that won't work.”"}
@@ -464,7 +519,7 @@ The simplest way to store the scraped data is by using :ref:`Feed exports
scrapy crawl quotes -O quotes.json
-That will generate an ``quotes.json`` file containing all scraped items,
+That will generate a ``quotes.json`` file containing all scraped items,
serialized in `JSON`_.
The ``-O`` command-line switch overwrites any existing file; use ``-o`` instead
@@ -472,13 +527,13 @@ to append new content to any existing file. However, appending to a JSON file
makes the file contents invalid JSON. When appending to a file, consider
using a different serialization format, such as `JSON Lines`_::
- scrapy crawl quotes -o quotes.jl
+ scrapy crawl quotes -o quotes.jsonl
The `JSON Lines`_ format is useful because it's stream-like, you can easily
append new records to it. It doesn't have the same problem of JSON when you run
twice. Also, as each record is a separate line, you can process big files
without having to fit everything in memory, there are tools like `JQ`_ to help
-doing that at the command-line.
+do that at the command-line.
In small projects (like the one in this tutorial), that should be enough.
However, if you want to perform more complex things with the scraped items, you
@@ -495,7 +550,7 @@ Following links
===============
Let's say, instead of just scraping the stuff from the first two pages
-from http://quotes.toscrape.com, you want quotes from all the pages in the website.
+from https://quotes.toscrape.com, you want quotes from all the pages in the website.
Now that you know how to extract data from pages, let's see how to follow links
from them.
@@ -521,17 +576,23 @@ This gets the anchor element, but we want the attribute ``href``. For that,
Scrapy supports a CSS extension that lets you select the attribute contents,
like this:
->>> response.css('li.next a::attr(href)').get()
-'/page/2/'
+.. code-block:: pycon
+
+ >>> response.css("li.next a::attr(href)").get()
+ '/page/2/'
There is also an ``attrib`` property available
(see :ref:`selecting-attributes` for more):
->>> response.css('li.next a').attrib['href']
-'/page/2/'
+.. code-block:: pycon
+
+ >>> response.css("li.next a").attrib["href"]
+ '/page/2/'
Let's see now our spider modified to recursively follow the link to the next
-page, extracting data from it::
+page, extracting data from it:
+
+.. code-block:: python
import scrapy
@@ -539,18 +600,18 @@ page, extracting data from it::
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
- 'http://quotes.toscrape.com/page/1/',
+ "https://quotes.toscrape.com/page/1/",
]
def parse(self, response):
- for quote in response.css('div.quote'):
+ for quote in response.css("div.quote"):
yield {
- 'text': quote.css('span.text::text').get(),
- 'author': quote.css('small.author::text').get(),
- 'tags': quote.css('div.tags a.tag::text').getall(),
+ "text": quote.css("span.text::text").get(),
+ "author": quote.css("small.author::text").get(),
+ "tags": quote.css("div.tags a.tag::text").getall(),
}
- next_page = response.css('li.next a::attr(href)').get()
+ next_page = response.css("li.next a::attr(href)").get()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
@@ -582,7 +643,9 @@ A shortcut for creating Requests
--------------------------------
As a shortcut for creating Request objects you can use
-:meth:`response.follow `::
+:meth:`response.follow `:
+
+.. code-block:: python
import scrapy
@@ -590,18 +653,18 @@ As a shortcut for creating Request objects you can use
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
- 'http://quotes.toscrape.com/page/1/',
+ "https://quotes.toscrape.com/page/1/",
]
def parse(self, response):
- for quote in response.css('div.quote'):
+ for quote in response.css("div.quote"):
yield {
- 'text': quote.css('span.text::text').get(),
- 'author': quote.css('span small::text').get(),
- 'tags': quote.css('div.tags a.tag::text').getall(),
+ "text": quote.css("span.text::text").get(),
+ "author": quote.css("span small::text").get(),
+ "tags": quote.css("div.tags a.tag::text").getall(),
}
- next_page = response.css('li.next a::attr(href)').get()
+ next_page = response.css("li.next a::attr(href)").get()
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
@@ -609,58 +672,72 @@ Unlike scrapy.Request, ``response.follow`` supports relative URLs directly - no
need to call urljoin. Note that ``response.follow`` just returns a Request
instance; you still have to yield this Request.
-You can also pass a selector to ``response.follow`` instead of a string;
-this selector should extract necessary attributes::
+.. skip: start
- for href in response.css('ul.pager a::attr(href)'):
+You can also pass a selector to ``response.follow`` instead of a string;
+this selector should extract necessary attributes:
+
+.. code-block:: python
+
+ for href in response.css("ul.pager a::attr(href)"):
yield response.follow(href, callback=self.parse)
For ```` elements there is a shortcut: ``response.follow`` uses their href
-attribute automatically. So the code can be shortened further::
+attribute automatically. So the code can be shortened further:
- for a in response.css('ul.pager a'):
+.. code-block:: python
+
+ for a in response.css("ul.pager a"):
yield response.follow(a, callback=self.parse)
To create multiple requests from an iterable, you can use
-:meth:`response.follow_all ` instead::
+:meth:`response.follow_all ` instead:
- anchors = response.css('ul.pager a')
+.. code-block:: python
+
+ anchors = response.css("ul.pager a")
yield from response.follow_all(anchors, callback=self.parse)
-or, shortening it further::
+or, shortening it further:
- yield from response.follow_all(css='ul.pager a', callback=self.parse)
+.. code-block:: python
+
+ yield from response.follow_all(css="ul.pager a", callback=self.parse)
+
+.. skip: end
More examples and patterns
--------------------------
Here is another spider that illustrates callbacks and following links,
-this time for scraping author information::
+this time for scraping author information:
+
+.. code-block:: python
import scrapy
class AuthorSpider(scrapy.Spider):
- name = 'author'
+ name = "author"
- start_urls = ['http://quotes.toscrape.com/']
+ start_urls = ["https://quotes.toscrape.com/"]
def parse(self, response):
- author_page_links = response.css('.author + a')
+ author_page_links = response.css(".author + a")
yield from response.follow_all(author_page_links, self.parse_author)
- pagination_links = response.css('li.next a')
+ pagination_links = response.css("li.next a")
yield from response.follow_all(pagination_links, self.parse)
def parse_author(self, response):
def extract_with_css(query):
- return response.css(query).get(default='').strip()
+ return response.css(query).get(default="").strip()
yield {
- 'name': extract_with_css('h3.author-title::text'),
- 'birthdate': extract_with_css('.author-born-date::text'),
- 'bio': extract_with_css('.author-description::text'),
+ "name": extract_with_css("h3.author-title::text"),
+ "birthdate": extract_with_css(".author-born-date::text"),
+ "bio": extract_with_css(".author-description::text"),
}
This spider will start from the main page, it will follow all the links to the
@@ -670,7 +747,7 @@ the pagination links with the ``parse`` callback as we saw before.
Here we're passing callbacks to
:meth:`response.follow_all ` as positional
arguments to make the code shorter; it also works for
-:class:`~scrapy.http.Request`.
+:class:`~scrapy.Request`.
The ``parse_author`` callback defines a helper function to extract and cleanup the
data from a CSS query and yields the Python dict with the author data.
@@ -708,7 +785,9 @@ spider attributes by default.
In this example, the value provided for the ``tag`` argument will be available
via ``self.tag``. You can use this to make your spider fetch only quotes
-with a specific tag, building the URL based on the argument::
+with a specific tag, building the URL based on the argument:
+
+.. code-block:: python
import scrapy
@@ -717,27 +796,27 @@ with a specific tag, building the URL based on the argument::
name = "quotes"
def start_requests(self):
- url = 'http://quotes.toscrape.com/'
- tag = getattr(self, 'tag', None)
+ url = "https://quotes.toscrape.com/"
+ tag = getattr(self, "tag", None)
if tag is not None:
- url = url + 'tag/' + tag
+ url = url + "tag/" + tag
yield scrapy.Request(url, self.parse)
def parse(self, response):
- for quote in response.css('div.quote'):
+ for quote in response.css("div.quote"):
yield {
- 'text': quote.css('span.text::text').get(),
- 'author': quote.css('small.author::text').get(),
+ "text": quote.css("span.text::text").get(),
+ "author": quote.css("small.author::text").get(),
}
- next_page = response.css('li.next a::attr(href)').get()
+ next_page = response.css("li.next a::attr(href)").get()
if next_page is not None:
yield response.follow(next_page, self.parse)
If you pass the ``tag=humor`` argument to this spider, you'll notice that it
will only visit URLs from the ``humor`` tag, such as
-``http://quotes.toscrape.com/tag/humor``.
+``https://quotes.toscrape.com/tag/humor``.
You can :ref:`learn more about handling spider arguments here `.
diff --git a/docs/news.rst b/docs/news.rst
index 850b323ef..65d9c5181 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -3,6 +3,1938 @@
Release notes
=============
+.. _release-2.11.0:
+
+Scrapy 2.11.0 (2023-09-18)
+--------------------------
+
+Highlights:
+
+- Spiders can now modify :ref:`settings ` in their
+ :meth:`~scrapy.Spider.from_crawler` methods, e.g. based on :ref:`spider
+ arguments `.
+
+- Periodic logging of stats.
+
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- Most of the initialization of :class:`scrapy.crawler.Crawler` instances is
+ now done in :meth:`~scrapy.crawler.Crawler.crawl`, so the state of
+ instances before that method is called is now different compared to older
+ Scrapy versions. We do not recommend using the
+ :class:`~scrapy.crawler.Crawler` instances before
+ :meth:`~scrapy.crawler.Crawler.crawl` is called. (:issue:`6038`)
+
+- :meth:`scrapy.Spider.from_crawler` is now called before the initialization
+ of various components previously initialized in
+ :meth:`scrapy.crawler.Crawler.__init__` and before the settings are
+ finalized and frozen. This change was needed to allow changing the settings
+ in :meth:`scrapy.Spider.from_crawler`. If you want to access the final
+ setting values and the initialized :class:`~scrapy.crawler.Crawler`
+ attributes in the spider code as early as possible you can do this in
+ :meth:`~scrapy.Spider.start_requests` or in a handler of the
+ :signal:`engine_started` signal. (:issue:`6038`)
+
+- The :meth:`TextResponse.json ` method now
+ requires the response to be in a valid JSON encoding (UTF-8, UTF-16, or
+ UTF-32). If you need to deal with JSON documents in an invalid encoding,
+ use ``json.loads(response.text)`` instead. (:issue:`6016`)
+
+- :class:`~scrapy.exporters.PythonItemExporter` used the binary output by
+ default but it no longer does. (:issue:`6006`, :issue:`6007`)
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+- Removed the binary export mode of
+ :class:`~scrapy.exporters.PythonItemExporter`, deprecated in Scrapy 1.1.0.
+ (:issue:`6006`, :issue:`6007`)
+
+ .. note:: If you are using this Scrapy version on Scrapy Cloud with a stack
+ that includes an older Scrapy version and get a "TypeError:
+ Unexpected options: binary" error, you may need to add
+ ``scrapinghub-entrypoint-scrapy >= 0.14.1`` to your project
+ requirements or switch to a stack that includes Scrapy 2.11.
+
+- Removed the ``CrawlerRunner.spiders`` attribute, deprecated in Scrapy
+ 1.0.0, use :attr:`CrawlerRunner.spider_loader
+ ` instead. (:issue:`6010`)
+
+Deprecations
+~~~~~~~~~~~~
+
+- Running :meth:`~scrapy.crawler.Crawler.crawl` more than once on the same
+ :class:`scrapy.crawler.Crawler` instance is now deprecated. (:issue:`1587`,
+ :issue:`6040`)
+
+New features
+~~~~~~~~~~~~
+
+- Spiders can now modify settings in their
+ :meth:`~scrapy.Spider.from_crawler` method, e.g. based on :ref:`spider
+ arguments `. (:issue:`1305`, :issue:`1580`, :issue:`2392`,
+ :issue:`3663`, :issue:`6038`)
+
+- Added the :class:`~scrapy.extensions.periodic_log.PeriodicLog` extension
+ which can be enabled to log stats and/or their differences periodically.
+ (:issue:`5926`)
+
+- Optimized the memory usage in :meth:`TextResponse.json
+ ` by removing unnecessary body decoding.
+ (:issue:`5968`, :issue:`6016`)
+
+- Links to ``.webp`` files are now ignored by :ref:`link extractors
+ `. (:issue:`6021`)
+
+Bug fixes
+~~~~~~~~~
+
+- Fixed logging enabled add-ons. (:issue:`6036`)
+
+- Fixed :class:`~scrapy.mail.MailSender` producing invalid message bodies
+ when the ``charset`` argument is passed to
+ :meth:`~scrapy.mail.MailSender.send`. (:issue:`5096`, :issue:`5118`)
+
+- Fixed an exception when accessing ``self.EXCEPTIONS_TO_RETRY`` from a
+ subclass of :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware`.
+ (:issue:`6049`, :issue:`6050`)
+
+- :meth:`scrapy.settings.BaseSettings.getdictorlist`, used to parse
+ :setting:`FEED_EXPORT_FIELDS`, now handles tuple values. (:issue:`6011`,
+ :issue:`6013`)
+
+- Calls to ``datetime.utcnow()``, no longer recommended to be used, have been
+ replaced with calls to ``datetime.now()`` with a timezone. (:issue:`6014`)
+
+Documentation
+~~~~~~~~~~~~~
+
+- Updated a deprecated function call in a pipeline example. (:issue:`6008`,
+ :issue:`6009`)
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Extended typing hints. (:issue:`6003`, :issue:`6005`, :issue:`6031`,
+ :issue:`6034`)
+
+- Pinned brotli_ to 1.0.9 for the PyPy tests as 1.1.0 breaks them.
+ (:issue:`6044`, :issue:`6045`)
+
+- Other CI and pre-commit improvements. (:issue:`6002`, :issue:`6013`,
+ :issue:`6046`)
+
+.. _release-2.10.1:
+
+Scrapy 2.10.1 (2023-08-30)
+--------------------------
+
+Marked ``Twisted >= 23.8.0`` as unsupported. (:issue:`6024`, :issue:`6026`)
+
+.. _release-2.10.0:
+
+Scrapy 2.10.0 (2023-08-04)
+--------------------------
+
+Highlights:
+
+- Added Python 3.12 support, dropped Python 3.7 support.
+
+- The new add-ons framework simplifies configuring 3rd-party components that
+ support it.
+
+- Exceptions to retry can now be configured.
+
+- Many fixes and improvements for feed exports.
+
+Modified requirements
+~~~~~~~~~~~~~~~~~~~~~
+
+- Dropped support for Python 3.7. (:issue:`5953`)
+
+- Added support for the upcoming Python 3.12. (:issue:`5984`)
+
+- Minimum versions increased for these dependencies:
+
+ - lxml_: 4.3.0 → 4.4.1
+
+ - cryptography_: 3.4.6 → 36.0.0
+
+- ``pkg_resources`` is no longer used. (:issue:`5956`, :issue:`5958`)
+
+- boto3_ is now recommended instead of botocore_ for exporting to S3.
+ (:issue:`5833`).
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- The value of the :setting:`FEED_STORE_EMPTY` setting is now ``True``
+ instead of ``False``. In earlier Scrapy versions empty files were created
+ even when this setting was ``False`` (which was a bug that is now fixed),
+ so the new default should keep the old behavior. (:issue:`872`,
+ :issue:`5847`)
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+- When a function is assigned to the :setting:`FEED_URI_PARAMS` setting,
+ returning ``None`` or modifying the ``params`` input parameter, deprecated
+ in Scrapy 2.6, is no longer supported. (:issue:`5994`, :issue:`5996`)
+
+- The ``scrapy.utils.reqser`` module, deprecated in Scrapy 2.6, is removed.
+ (:issue:`5994`, :issue:`5996`)
+
+- The ``scrapy.squeues`` classes ``PickleFifoDiskQueueNonRequest``,
+ ``PickleLifoDiskQueueNonRequest``, ``MarshalFifoDiskQueueNonRequest``,
+ and ``MarshalLifoDiskQueueNonRequest``, deprecated in
+ Scrapy 2.6, are removed. (:issue:`5994`, :issue:`5996`)
+
+- The property ``open_spiders`` and the methods ``has_capacity`` and
+ ``schedule`` of :class:`scrapy.core.engine.ExecutionEngine`,
+ deprecated in Scrapy 2.6, are removed. (:issue:`5994`, :issue:`5998`)
+
+- Passing a ``spider`` argument to the
+ :meth:`~scrapy.core.engine.ExecutionEngine.spider_is_idle`,
+ :meth:`~scrapy.core.engine.ExecutionEngine.crawl` and
+ :meth:`~scrapy.core.engine.ExecutionEngine.download` methods of
+ :class:`scrapy.core.engine.ExecutionEngine`, deprecated in Scrapy 2.6, is
+ no longer supported. (:issue:`5994`, :issue:`5998`)
+
+Deprecations
+~~~~~~~~~~~~
+
+- :class:`scrapy.utils.datatypes.CaselessDict` is deprecated, use
+ :class:`scrapy.utils.datatypes.CaseInsensitiveDict` instead.
+ (:issue:`5146`)
+
+- Passing the ``custom`` argument to
+ :func:`scrapy.utils.conf.build_component_list` is deprecated, it was used
+ in the past to merge ``FOO`` and ``FOO_BASE`` setting values but now Scrapy
+ uses :func:`scrapy.settings.BaseSettings.getwithbase` to do the same.
+ Code that uses this argument and cannot be switched to ``getwithbase()``
+ can be switched to merging the values explicitly. (:issue:`5726`,
+ :issue:`5923`)
+
+New features
+~~~~~~~~~~~~
+
+- Added support for :ref:`Scrapy add-ons `. (:issue:`5950`)
+
+- Added the :setting:`RETRY_EXCEPTIONS` setting that configures which
+ exceptions will be retried by
+ :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware`.
+ (:issue:`2701`, :issue:`5929`)
+
+- Added the possiiblity to close the spider if no items were produced in the
+ specified time, configured by :setting:`CLOSESPIDER_TIMEOUT_NO_ITEM`.
+ (:issue:`5979`)
+
+- Added support for the :setting:`AWS_REGION_NAME` setting to feed exports.
+ (:issue:`5980`)
+
+- Added support for using :class:`pathlib.Path` objects that refer to
+ absolute Windows paths in the :setting:`FEEDS` setting. (:issue:`5939`)
+
+Bug fixes
+~~~~~~~~~
+
+- Fixed creating empty feeds even with ``FEED_STORE_EMPTY=False``.
+ (:issue:`872`, :issue:`5847`)
+
+- Fixed using absolute Windows paths when specifying output files.
+ (:issue:`5969`, :issue:`5971`)
+
+- Fixed problems with uploading large files to S3 by switching to multipart
+ uploads (requires boto3_). (:issue:`960`, :issue:`5735`, :issue:`5833`)
+
+- Fixed the JSON exporter writing extra commas when some exceptions occur.
+ (:issue:`3090`, :issue:`5952`)
+
+- Fixed the "read of closed file" error in the CSV exporter. (:issue:`5043`,
+ :issue:`5705`)
+
+- Fixed an error when a component added by the class object throws
+ :exc:`~scrapy.exceptions.NotConfigured` with a message. (:issue:`5950`,
+ :issue:`5992`)
+
+- Added the missing :meth:`scrapy.settings.BaseSettings.pop` method.
+ (:issue:`5959`, :issue:`5960`, :issue:`5963`)
+
+- Added :class:`~scrapy.utils.datatypes.CaseInsensitiveDict` as a replacement
+ for :class:`~scrapy.utils.datatypes.CaselessDict` that fixes some API
+ inconsistencies. (:issue:`5146`)
+
+Documentation
+~~~~~~~~~~~~~
+
+- Documented :meth:`scrapy.Spider.update_settings`. (:issue:`5745`,
+ :issue:`5846`)
+
+- Documented possible problems with early Twisted reactor installation and
+ their solutions. (:issue:`5981`, :issue:`6000`)
+
+- Added examples of making additional requests in callbacks. (:issue:`5927`)
+
+- Improved the feed export docs. (:issue:`5579`, :issue:`5931`)
+
+- Clarified the docs about request objects on redirection. (:issue:`5707`,
+ :issue:`5937`)
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Added support for running tests against the installed Scrapy version.
+ (:issue:`4914`, :issue:`5949`)
+
+- Extended typing hints. (:issue:`5925`, :issue:`5977`)
+
+- Fixed the ``test_utils_asyncio.AsyncioTest.test_set_asyncio_event_loop``
+ test. (:issue:`5951`)
+
+- Fixed the ``test_feedexport.BatchDeliveriesTest.test_batch_path_differ``
+ test on Windows. (:issue:`5847`)
+
+- Enabled CI runs for Python 3.11 on Windows. (:issue:`5999`)
+
+- Simplified skipping tests that depend on ``uvloop``. (:issue:`5984`)
+
+- Fixed the ``extra-deps-pinned`` tox env. (:issue:`5948`)
+
+- Implemented cleanups. (:issue:`5965`, :issue:`5986`)
+
+.. _release-2.9.0:
+
+Scrapy 2.9.0 (2023-05-08)
+-------------------------
+
+Highlights:
+
+- Per-domain download settings.
+- Compatibility with new cryptography_ and new parsel_.
+- JMESPath selectors from the new parsel_.
+- Bug fixes.
+
+Deprecations
+~~~~~~~~~~~~
+
+- :class:`scrapy.extensions.feedexport._FeedSlot` is renamed to
+ :class:`scrapy.extensions.feedexport.FeedSlot` and the old name is
+ deprecated. (:issue:`5876`)
+
+New features
+~~~~~~~~~~~~
+
+- Settings corresponding to :setting:`DOWNLOAD_DELAY`,
+ :setting:`CONCURRENT_REQUESTS_PER_DOMAIN` and
+ :setting:`RANDOMIZE_DOWNLOAD_DELAY` can now be set on a per-domain basis
+ via the new :setting:`DOWNLOAD_SLOTS` setting. (:issue:`5328`)
+
+- Added :meth:`TextResponse.jmespath`, a shortcut for JMESPath selectors
+ available since parsel_ 1.8.1. (:issue:`5894`, :issue:`5915`)
+
+- Added :signal:`feed_slot_closed` and :signal:`feed_exporter_closed`
+ signals. (:issue:`5876`)
+
+- Added :func:`scrapy.utils.request.request_to_curl`, a function to produce a
+ curl command from a :class:`~scrapy.Request` object. (:issue:`5892`)
+
+- Values of :setting:`FILES_STORE` and :setting:`IMAGES_STORE` can now be
+ :class:`pathlib.Path` instances. (:issue:`5801`)
+
+Bug fixes
+~~~~~~~~~
+
+- Fixed a warning with Parsel 1.8.1+. (:issue:`5903`, :issue:`5918`)
+
+- Fixed an error when using feed postprocessing with S3 storage.
+ (:issue:`5500`, :issue:`5581`)
+
+- Added the missing :meth:`scrapy.settings.BaseSettings.setdefault` method.
+ (:issue:`5811`, :issue:`5821`)
+
+- Fixed an error when using cryptography_ 40.0.0+ and
+ :setting:`DOWNLOADER_CLIENT_TLS_VERBOSE_LOGGING` is enabled.
+ (:issue:`5857`, :issue:`5858`)
+
+- The checksums returned by :class:`~scrapy.pipelines.files.FilesPipeline`
+ for files on Google Cloud Storage are no longer Base64-encoded.
+ (:issue:`5874`, :issue:`5891`)
+
+- :func:`scrapy.utils.request.request_from_curl` now supports $-prefixed
+ string values for the curl ``--data-raw`` argument, which are produced by
+ browsers for data that includes certain symbols. (:issue:`5899`,
+ :issue:`5901`)
+
+- The :command:`parse` command now also works with async generator callbacks.
+ (:issue:`5819`, :issue:`5824`)
+
+- The :command:`genspider` command now properly works with HTTPS URLs.
+ (:issue:`3553`, :issue:`5808`)
+
+- Improved handling of asyncio loops. (:issue:`5831`, :issue:`5832`)
+
+- :class:`LinkExtractor `
+ now skips certain malformed URLs instead of raising an exception.
+ (:issue:`5881`)
+
+- :func:`scrapy.utils.python.get_func_args` now supports more types of
+ callables. (:issue:`5872`, :issue:`5885`)
+
+- Fixed an error when processing non-UTF8 values of ``Content-Type`` headers.
+ (:issue:`5914`, :issue:`5917`)
+
+- Fixed an error breaking user handling of send failures in
+ :meth:`scrapy.mail.MailSender.send()`. (:issue:`1611`, :issue:`5880`)
+
+Documentation
+~~~~~~~~~~~~~
+
+- Expanded contributing docs. (:issue:`5109`, :issue:`5851`)
+
+- Added blacken-docs_ to pre-commit and reformatted the docs with it.
+ (:issue:`5813`, :issue:`5816`)
+
+- Fixed a JS issue. (:issue:`5875`, :issue:`5877`)
+
+- Fixed ``make htmlview``. (:issue:`5878`, :issue:`5879`)
+
+- Fixed typos and other small errors. (:issue:`5827`, :issue:`5839`,
+ :issue:`5883`, :issue:`5890`, :issue:`5895`, :issue:`5904`)
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Extended typing hints. (:issue:`5805`, :issue:`5889`, :issue:`5896`)
+
+- Tests for most of the examples in the docs are now run as a part of CI,
+ found problems were fixed. (:issue:`5816`, :issue:`5826`, :issue:`5919`)
+
+- Removed usage of deprecated Python classes. (:issue:`5849`)
+
+- Silenced ``include-ignored`` warnings from coverage. (:issue:`5820`)
+
+- Fixed a random failure of the ``test_feedexport.test_batch_path_differ``
+ test. (:issue:`5855`, :issue:`5898`)
+
+- Updated docstrings to match output produced by parsel_ 1.8.1 so that they
+ don't cause test failures. (:issue:`5902`, :issue:`5919`)
+
+- Other CI and pre-commit improvements. (:issue:`5802`, :issue:`5823`,
+ :issue:`5908`)
+
+.. _blacken-docs: https://github.com/adamchainz/blacken-docs
+
+.. _release-2.8.0:
+
+Scrapy 2.8.0 (2023-02-02)
+-------------------------
+
+This is a maintenance release, with minor features, bug fixes, and cleanups.
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+- The ``scrapy.utils.gz.read1`` function, deprecated in Scrapy 2.0, has now
+ been removed. Use the :meth:`~io.BufferedIOBase.read1` method of
+ :class:`~gzip.GzipFile` instead.
+ (:issue:`5719`)
+
+- The ``scrapy.utils.python.to_native_str`` function, deprecated in Scrapy
+ 2.0, has now been removed. Use :func:`scrapy.utils.python.to_unicode`
+ instead.
+ (:issue:`5719`)
+
+- The ``scrapy.utils.python.MutableChain.next`` method, deprecated in Scrapy
+ 2.0, has now been removed. Use
+ :meth:`~scrapy.utils.python.MutableChain.__next__` instead.
+ (:issue:`5719`)
+
+- The ``scrapy.linkextractors.FilteringLinkExtractor`` class, deprecated
+ in Scrapy 2.0, has now been removed. Use
+ :class:`LinkExtractor `
+ instead.
+ (:issue:`5720`)
+
+- Support for using environment variables prefixed with ``SCRAPY_`` to
+ override settings, deprecated in Scrapy 2.0, has now been removed.
+ (:issue:`5724`)
+
+- Support for the ``noconnect`` query string argument in proxy URLs,
+ deprecated in Scrapy 2.0, has now been removed. We expect proxies that used
+ to need it to work fine without it.
+ (:issue:`5731`)
+
+- The ``scrapy.utils.python.retry_on_eintr`` function, deprecated in Scrapy
+ 2.3, has now been removed.
+ (:issue:`5719`)
+
+- The ``scrapy.utils.python.WeakKeyCache`` class, deprecated in Scrapy 2.4,
+ has now been removed.
+ (:issue:`5719`)
+
+- The ``scrapy.utils.boto.is_botocore()`` function, deprecated in Scrapy 2.4,
+ has now been removed.
+ (:issue:`5719`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+- :exc:`scrapy.pipelines.images.NoimagesDrop` is now deprecated.
+ (:issue:`5368`, :issue:`5489`)
+
+- :meth:`ImagesPipeline.convert_image
+ ` must now accept a
+ ``response_body`` parameter.
+ (:issue:`3055`, :issue:`3689`, :issue:`4753`)
+
+
+New features
+~~~~~~~~~~~~
+
+- Applied black_ coding style to files generated with the
+ :command:`genspider` and :command:`startproject` commands.
+ (:issue:`5809`, :issue:`5814`)
+
+ .. _black: https://black.readthedocs.io/en/stable/
+
+- :setting:`FEED_EXPORT_ENCODING` is now set to ``"utf-8"`` in the
+ ``settings.py`` file that the :command:`startproject` command generates.
+ With this value, JSON exports won’t force the use of escape sequences for
+ non-ASCII characters.
+ (:issue:`5797`, :issue:`5800`)
+
+- The :class:`~scrapy.extensions.memusage.MemoryUsage` extension now logs the
+ peak memory usage during checks, and the binary unit MiB is now used to
+ avoid confusion.
+ (:issue:`5717`, :issue:`5722`, :issue:`5727`)
+
+- The ``callback`` parameter of :class:`~scrapy.http.Request` can now be set
+ to :func:`scrapy.http.request.NO_CALLBACK`, to distinguish it from
+ ``None``, as the latter indicates that the default spider callback
+ (:meth:`~scrapy.Spider.parse`) is to be used.
+ (:issue:`5798`)
+
+
+Bug fixes
+~~~~~~~~~
+
+- Enabled unsafe legacy SSL renegotiation to fix access to some outdated
+ websites.
+ (:issue:`5491`, :issue:`5790`)
+
+- Fixed STARTTLS-based email delivery not working with Twisted 21.2.0 and
+ better.
+ (:issue:`5386`, :issue:`5406`)
+
+- Fixed the :meth:`finish_exporting` method of :ref:`item exporters
+ ` not being called for empty files.
+ (:issue:`5537`, :issue:`5758`)
+
+- Fixed HTTP/2 responses getting only the last value for a header when
+ multiple headers with the same name are received.
+ (:issue:`5777`)
+
+- Fixed an exception raised by the :command:`shell` command on some cases
+ when :ref:`using asyncio `.
+ (:issue:`5740`, :issue:`5742`, :issue:`5748`, :issue:`5759`, :issue:`5760`,
+ :issue:`5771`)
+
+- When using :class:`~scrapy.spiders.CrawlSpider`, callback keyword arguments
+ (``cb_kwargs``) added to a request in the ``process_request`` callback of a
+ :class:`~scrapy.spiders.Rule` will no longer be ignored.
+ (:issue:`5699`)
+
+- The :ref:`images pipeline ` no longer re-encodes JPEG
+ files.
+ (:issue:`3055`, :issue:`3689`, :issue:`4753`)
+
+- Fixed the handling of transparent WebP images by the :ref:`images pipeline
+ `.
+ (:issue:`3072`, :issue:`5766`, :issue:`5767`)
+
+- :func:`scrapy.shell.inspect_response` no longer inhibits ``SIGINT``
+ (Ctrl+C).
+ (:issue:`2918`)
+
+- :class:`LinkExtractor `
+ with ``unique=False`` no longer filters out links that have identical URL
+ *and* text.
+ (:issue:`3798`, :issue:`3799`, :issue:`4695`, :issue:`5458`)
+
+- :class:`~scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware` now
+ ignores URL protocols that do not support ``robots.txt`` (``data://``,
+ ``file://``).
+ (:issue:`5807`)
+
+- Silenced the ``filelock`` debug log messages introduced in Scrapy 2.6.
+ (:issue:`5753`, :issue:`5754`)
+
+- Fixed the output of ``scrapy -h`` showing an unintended ``**commands**``
+ line.
+ (:issue:`5709`, :issue:`5711`, :issue:`5712`)
+
+- Made the active project indication in the output of :ref:`commands
+ ` more clear.
+ (:issue:`5715`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+- Documented how to :ref:`debug spiders from Visual Studio Code
+ `.
+ (:issue:`5721`)
+
+- Documented how :setting:`DOWNLOAD_DELAY` affects per-domain concurrency.
+ (:issue:`5083`, :issue:`5540`)
+
+- Improved consistency.
+ (:issue:`5761`)
+
+- Fixed typos.
+ (:issue:`5714`, :issue:`5744`, :issue:`5764`)
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Applied :ref:`black coding style `, sorted import statements,
+ and introduced :ref:`pre-commit `.
+ (:issue:`4654`, :issue:`4658`, :issue:`5734`, :issue:`5737`, :issue:`5806`,
+ :issue:`5810`)
+
+- Switched from :mod:`os.path` to :mod:`pathlib`.
+ (:issue:`4916`, :issue:`4497`, :issue:`5682`)
+
+- Addressed many issues reported by Pylint.
+ (:issue:`5677`)
+
+- Improved code readability.
+ (:issue:`5736`)
+
+- Improved package metadata.
+ (:issue:`5768`)
+
+- Removed direct invocations of ``setup.py``.
+ (:issue:`5774`, :issue:`5776`)
+
+- Removed unnecessary :class:`~collections.OrderedDict` usages.
+ (:issue:`5795`)
+
+- Removed unnecessary ``__str__`` definitions.
+ (:issue:`5150`)
+
+- Removed obsolete code and comments.
+ (:issue:`5725`, :issue:`5729`, :issue:`5730`, :issue:`5732`)
+
+- Fixed test and CI issues.
+ (:issue:`5749`, :issue:`5750`, :issue:`5756`, :issue:`5762`, :issue:`5765`,
+ :issue:`5780`, :issue:`5781`, :issue:`5782`, :issue:`5783`, :issue:`5785`,
+ :issue:`5786`)
+
+
+.. _release-2.7.1:
+
+Scrapy 2.7.1 (2022-11-02)
+-------------------------
+
+New features
+~~~~~~~~~~~~
+
+- Relaxed the restriction introduced in 2.6.2 so that the
+ ``Proxy-Authorization`` header can again be set explicitly, as long as the
+ proxy URL in the :reqmeta:`proxy` metadata has no other credentials, and
+ for as long as that proxy URL remains the same; this restores compatibility
+ with scrapy-zyte-smartproxy 2.1.0 and older (:issue:`5626`).
+
+Bug fixes
+~~~~~~~~~
+
+- Using ``-O``/``--overwrite-output`` and ``-t``/``--output-format`` options
+ together now produces an error instead of ignoring the former option
+ (:issue:`5516`, :issue:`5605`).
+
+- Replaced deprecated :mod:`asyncio` APIs that implicitly use the current
+ event loop with code that explicitly requests a loop from the event loop
+ policy (:issue:`5685`, :issue:`5689`).
+
+- Fixed uses of deprecated Scrapy APIs in Scrapy itself (:issue:`5588`,
+ :issue:`5589`).
+
+- Fixed uses of a deprecated Pillow API (:issue:`5684`, :issue:`5692`).
+
+- Improved code that checks if generators return values, so that it no longer
+ fails on decorated methods and partial methods (:issue:`5323`,
+ :issue:`5592`, :issue:`5599`, :issue:`5691`).
+
+Documentation
+~~~~~~~~~~~~~
+
+- Upgraded the Code of Conduct to Contributor Covenant v2.1 (:issue:`5698`).
+
+- Fixed typos (:issue:`5681`, :issue:`5694`).
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Re-enabled some erroneously disabled flake8 checks (:issue:`5688`).
+
+- Ignored harmless deprecation warnings from :mod:`typing` in tests
+ (:issue:`5686`, :issue:`5697`).
+
+- Modernized our CI configuration (:issue:`5695`, :issue:`5696`).
+
+
+.. _release-2.7.0:
+
+Scrapy 2.7.0 (2022-10-17)
+-----------------------------
+
+Highlights:
+
+- Added Python 3.11 support, dropped Python 3.6 support
+- Improved support for :ref:`asynchronous callbacks `
+- :ref:`Asyncio support ` is enabled by default on new
+ projects
+- Output names of item fields can now be arbitrary strings
+- Centralized :ref:`request fingerprinting `
+ configuration is now possible
+
+Modified requirements
+~~~~~~~~~~~~~~~~~~~~~
+
+Python 3.7 or greater is now required; support for Python 3.6 has been dropped.
+Support for the upcoming Python 3.11 has been added.
+
+The minimum required version of some dependencies has changed as well:
+
+- lxml_: 3.5.0 → 4.3.0
+
+- Pillow_ (:ref:`images pipeline `): 4.0.0 → 7.1.0
+
+- zope.interface_: 5.0.0 → 5.1.0
+
+(:issue:`5512`, :issue:`5514`, :issue:`5524`, :issue:`5563`, :issue:`5664`,
+:issue:`5670`, :issue:`5678`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+- :meth:`ImagesPipeline.thumb_path
+ ` must now accept an
+ ``item`` parameter (:issue:`5504`, :issue:`5508`).
+
+- The ``scrapy.downloadermiddlewares.decompression`` module is now
+ deprecated (:issue:`5546`, :issue:`5547`).
+
+
+New features
+~~~~~~~~~~~~
+
+- The
+ :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output`
+ method of :ref:`spider middlewares ` can now be
+ defined as an :term:`asynchronous generator` (:issue:`4978`).
+
+- The output of :class:`~scrapy.Request` callbacks defined as
+ :ref:`coroutines ` is now processed asynchronously
+ (:issue:`4978`).
+
+- :class:`~scrapy.spiders.crawl.CrawlSpider` now supports :ref:`asynchronous
+ callbacks ` (:issue:`5657`).
+
+- New projects created with the :command:`startproject` command have
+ :ref:`asyncio support ` enabled by default (:issue:`5590`,
+ :issue:`5679`).
+
+- The :setting:`FEED_EXPORT_FIELDS` setting can now be defined as a
+ dictionary to customize the output name of item fields, lifting the
+ restriction that required output names to be valid Python identifiers, e.g.
+ preventing them to have whitespace (:issue:`1008`, :issue:`3266`,
+ :issue:`3696`).
+
+- You can now customize :ref:`request fingerprinting `
+ through the new :setting:`REQUEST_FINGERPRINTER_CLASS` setting, instead of
+ having to change it on every Scrapy component that relies on request
+ fingerprinting (:issue:`900`, :issue:`3420`, :issue:`4113`, :issue:`4762`,
+ :issue:`4524`).
+
+- ``jsonl`` is now supported and encouraged as a file extension for `JSON
+ Lines`_ files (:issue:`4848`).
+
+ .. _JSON Lines: https://jsonlines.org/
+
+- :meth:`ImagesPipeline.thumb_path
+ ` now receives the
+ source :ref:`item ` (:issue:`5504`, :issue:`5508`).
+
+
+Bug fixes
+~~~~~~~~~
+
+- When using Google Cloud Storage with a :ref:`media pipeline
+ `, :setting:`FILES_EXPIRES` now also works when
+ :setting:`FILES_STORE` does not point at the root of your Google Cloud
+ Storage bucket (:issue:`5317`, :issue:`5318`).
+
+- The :command:`parse` command now supports :ref:`asynchronous callbacks
+ ` (:issue:`5424`, :issue:`5577`).
+
+- When using the :command:`parse` command with a URL for which there is no
+ available spider, an exception is no longer raised (:issue:`3264`,
+ :issue:`3265`, :issue:`5375`, :issue:`5376`, :issue:`5497`).
+
+- :class:`~scrapy.http.TextResponse` now gives higher priority to the `byte
+ order mark`_ when determining the text encoding of the response body,
+ following the `HTML living standard`_ (:issue:`5601`, :issue:`5611`).
+
+ .. _byte order mark: https://en.wikipedia.org/wiki/Byte_order_mark
+ .. _HTML living standard: https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding
+
+- MIME sniffing takes the response body into account in FTP and HTTP/1.0
+ requests, as well as in cached requests (:issue:`4873`).
+
+- MIME sniffing now detects valid HTML 5 documents even if the ``html`` tag
+ is missing (:issue:`4873`).
+
+- An exception is now raised if :setting:`ASYNCIO_EVENT_LOOP` has a value
+ that does not match the asyncio event loop actually installed
+ (:issue:`5529`).
+
+- Fixed :meth:`Headers.getlist `
+ returning only the last header (:issue:`5515`, :issue:`5526`).
+
+- Fixed :class:`LinkExtractor
+ ` not ignoring the
+ ``tar.gz`` file extension by default (:issue:`1837`, :issue:`2067`,
+ :issue:`4066`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+- Clarified the return type of :meth:`Spider.parse `
+ (:issue:`5602`, :issue:`5608`).
+
+- To enable
+ :class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`
+ to do `brotli compression`_, installing brotli_ is now recommended instead
+ of installing brotlipy_, as the former provides a more recent version of
+ brotli.
+
+ .. _brotli: https://github.com/google/brotli
+ .. _brotli compression: https://www.ietf.org/rfc/rfc7932.txt
+
+- :ref:`Signal documentation ` now mentions :ref:`coroutine
+ support ` and uses it in code examples (:issue:`4852`,
+ :issue:`5358`).
+
+- :ref:`bans` now recommends `Common Crawl`_ instead of `Google cache`_
+ (:issue:`3582`, :issue:`5432`).
+
+ .. _Common Crawl: https://commoncrawl.org/
+ .. _Google cache: http://www.googleguide.com/cached_pages.html
+
+- The new :ref:`topics-components` topic covers enforcing requirements on
+ Scrapy components, like :ref:`downloader middlewares
+ `, :ref:`extensions `,
+ :ref:`item pipelines `, :ref:`spider middlewares
+ `, and more; :ref:`enforce-asyncio-requirement`
+ has also been added (:issue:`4978`).
+
+- :ref:`topics-settings` now indicates that setting values must be
+ :ref:`picklable ` (:issue:`5607`, :issue:`5629`).
+
+- Removed outdated documentation (:issue:`5446`, :issue:`5373`,
+ :issue:`5369`, :issue:`5370`, :issue:`5554`).
+
+- Fixed typos (:issue:`5442`, :issue:`5455`, :issue:`5457`, :issue:`5461`,
+ :issue:`5538`, :issue:`5553`, :issue:`5558`, :issue:`5624`, :issue:`5631`).
+
+- Fixed other issues (:issue:`5283`, :issue:`5284`, :issue:`5559`,
+ :issue:`5567`, :issue:`5648`, :issue:`5659`, :issue:`5665`).
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+- Added a continuous integration job to run `twine check`_ (:issue:`5655`,
+ :issue:`5656`).
+
+ .. _twine check: https://twine.readthedocs.io/en/stable/#twine-check
+
+- Addressed test issues and warnings (:issue:`5560`, :issue:`5561`,
+ :issue:`5612`, :issue:`5617`, :issue:`5639`, :issue:`5645`, :issue:`5662`,
+ :issue:`5671`, :issue:`5675`).
+
+- Cleaned up code (:issue:`4991`, :issue:`4995`, :issue:`5451`,
+ :issue:`5487`, :issue:`5542`, :issue:`5667`, :issue:`5668`, :issue:`5672`).
+
+- Applied minor code improvements (:issue:`5661`).
+
+
+.. _release-2.6.3:
+
+Scrapy 2.6.3 (2022-09-27)
+-------------------------
+
+- Added support for pyOpenSSL_ 22.1.0, removing support for SSLv3
+ (:issue:`5634`, :issue:`5635`, :issue:`5636`).
+
+- Upgraded the minimum versions of the following dependencies:
+
+ - cryptography_: 2.0 → 3.3
+
+ - pyOpenSSL_: 16.2.0 → 21.0.0
+
+ - service_identity_: 16.0.0 → 18.1.0
+
+ - Twisted_: 17.9.0 → 18.9.0
+
+ - zope.interface_: 4.1.3 → 5.0.0
+
+ (:issue:`5621`, :issue:`5632`)
+
+- Fixes test and documentation issues (:issue:`5612`, :issue:`5617`,
+ :issue:`5631`).
+
+
+.. _release-2.6.2:
+
+Scrapy 2.6.2 (2022-07-25)
+-------------------------
+
+**Security bug fix:**
+
+- When :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware`
+ processes a request with :reqmeta:`proxy` metadata, and that
+ :reqmeta:`proxy` metadata includes proxy credentials,
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` sets
+ the ``Proxy-Authorization`` header, but only if that header is not already
+ set.
+
+ There are third-party proxy-rotation downloader middlewares that set
+ different :reqmeta:`proxy` metadata every time they process a request.
+
+ Because of request retries and redirects, the same request can be processed
+ by downloader middlewares more than once, including both
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` and
+ any third-party proxy-rotation downloader middleware.
+
+ These third-party proxy-rotation downloader middlewares could change the
+ :reqmeta:`proxy` metadata of a request to a new value, but fail to remove
+ the ``Proxy-Authorization`` header from the previous value of the
+ :reqmeta:`proxy` metadata, causing the credentials of one proxy to be sent
+ to a different proxy.
+
+ To prevent the unintended leaking of proxy credentials, the behavior of
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` is now
+ as follows when processing a request:
+
+ - If the request being processed defines :reqmeta:`proxy` metadata that
+ includes credentials, the ``Proxy-Authorization`` header is always
+ updated to feature those credentials.
+
+ - If the request being processed defines :reqmeta:`proxy` metadata
+ without credentials, the ``Proxy-Authorization`` header is removed
+ *unless* it was originally defined for the same proxy URL.
+
+ To remove proxy credentials while keeping the same proxy URL, remove
+ the ``Proxy-Authorization`` header.
+
+ - If the request has no :reqmeta:`proxy` metadata, or that metadata is a
+ falsy value (e.g. ``None``), the ``Proxy-Authorization`` header is
+ removed.
+
+ It is no longer possible to set a proxy URL through the
+ :reqmeta:`proxy` metadata but set the credentials through the
+ ``Proxy-Authorization`` header. Set proxy credentials through the
+ :reqmeta:`proxy` metadata instead.
+
+Also fixes the following regressions introduced in 2.6.0:
+
+- :class:`~scrapy.crawler.CrawlerProcess` supports again crawling multiple
+ spiders (:issue:`5435`, :issue:`5436`)
+
+- Installing a Twisted reactor before Scrapy does (e.g. importing
+ :mod:`twisted.internet.reactor` somewhere at the module level) no longer
+ prevents Scrapy from starting, as long as a different reactor is not
+ specified in :setting:`TWISTED_REACTOR` (:issue:`5525`, :issue:`5528`)
+
+- Fixed an exception that was being logged after the spider finished under
+ certain conditions (:issue:`5437`, :issue:`5440`)
+
+- The ``--output``/``-o`` command-line parameter supports again a value
+ starting with a hyphen (:issue:`5444`, :issue:`5445`)
+
+- The ``scrapy parse -h`` command no longer throws an error (:issue:`5481`,
+ :issue:`5482`)
+
+
+.. _release-2.6.1:
+
+Scrapy 2.6.1 (2022-03-01)
+-------------------------
+
+Fixes a regression introduced in 2.6.0 that would unset the request method when
+following redirects.
+
+
+.. _release-2.6.0:
+
+Scrapy 2.6.0 (2022-03-01)
+-------------------------
+
+Highlights:
+
+* :ref:`Security fixes for cookie handling <2.6-security-fixes>`
+
+* Python 3.10 support
+
+* :ref:`asyncio support ` is no longer considered
+ experimental, and works out-of-the-box on Windows regardless of your Python
+ version
+
+* Feed exports now support :class:`pathlib.Path` output paths and per-feed
+ :ref:`item filtering ` and
+ :ref:`post-processing `
+
+.. _2.6-security-fixes:
+
+Security bug fixes
+~~~~~~~~~~~~~~~~~~
+
+- When a :class:`~scrapy.http.Request` object with cookies defined gets a
+ redirect response causing a new :class:`~scrapy.http.Request` object to be
+ scheduled, the cookies defined in the original
+ :class:`~scrapy.http.Request` object are no longer copied into the new
+ :class:`~scrapy.http.Request` object.
+
+ If you manually set the ``Cookie`` header on a
+ :class:`~scrapy.http.Request` object and the domain name of the redirect
+ URL is not an exact match for the domain of the URL of the original
+ :class:`~scrapy.http.Request` object, your ``Cookie`` header is now dropped
+ from the new :class:`~scrapy.http.Request` object.
+
+ The old behavior could be exploited by an attacker to gain access to your
+ cookies. Please, see the `cjvr-mfj7-j4j8 security advisory`_ for more
+ information.
+
+ .. _cjvr-mfj7-j4j8 security advisory: https://github.com/scrapy/scrapy/security/advisories/GHSA-cjvr-mfj7-j4j8
+
+ .. note:: It is still possible to enable the sharing of cookies between
+ different domains with a shared domain suffix (e.g.
+ ``example.com`` and any subdomain) by defining the shared domain
+ suffix (e.g. ``example.com``) as the cookie domain when defining
+ your cookies. See the documentation of the
+ :class:`~scrapy.http.Request` class for more information.
+
+- When the domain of a cookie, either received in the ``Set-Cookie`` header
+ of a response or defined in a :class:`~scrapy.http.Request` object, is set
+ to a `public suffix `_, the cookie is now
+ ignored unless the cookie domain is the same as the request domain.
+
+ The old behavior could be exploited by an attacker to inject cookies from a
+ controlled domain into your cookiejar that could be sent to other domains
+ not controlled by the attacker. Please, see the `mfjm-vh54-3f96 security
+ advisory`_ for more information.
+
+ .. _mfjm-vh54-3f96 security advisory: https://github.com/scrapy/scrapy/security/advisories/GHSA-mfjm-vh54-3f96
+
+
+Modified requirements
+~~~~~~~~~~~~~~~~~~~~~
+
+- The h2_ dependency is now optional, only needed to
+ :ref:`enable HTTP/2 support `. (:issue:`5113`)
+
+ .. _h2: https://pypi.org/project/h2/
+
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- The ``formdata`` parameter of :class:`~scrapy.FormRequest`, if specified
+ for a non-POST request, now overrides the URL query string, instead of
+ being appended to it. (:issue:`2919`, :issue:`3579`)
+
+- When a function is assigned to the :setting:`FEED_URI_PARAMS` setting, now
+ the return value of that function, and not the ``params`` input parameter,
+ will determine the feed URI parameters, unless that return value is
+ ``None``. (:issue:`4962`, :issue:`4966`)
+
+- In :class:`scrapy.core.engine.ExecutionEngine`, methods
+ :meth:`~scrapy.core.engine.ExecutionEngine.crawl`,
+ :meth:`~scrapy.core.engine.ExecutionEngine.download`,
+ :meth:`~scrapy.core.engine.ExecutionEngine.schedule`,
+ and :meth:`~scrapy.core.engine.ExecutionEngine.spider_is_idle`
+ now raise :exc:`RuntimeError` if called before
+ :meth:`~scrapy.core.engine.ExecutionEngine.open_spider`. (:issue:`5090`)
+
+ These methods used to assume that
+ :attr:`ExecutionEngine.slot ` had
+ been defined by a prior call to
+ :meth:`~scrapy.core.engine.ExecutionEngine.open_spider`, so they were
+ raising :exc:`AttributeError` instead.
+
+- If the API of the configured :ref:`scheduler ` does not
+ meet expectations, :exc:`TypeError` is now raised at startup time. Before,
+ other exceptions would be raised at run time. (:issue:`3559`)
+
+- The ``_encoding`` field of serialized :class:`~scrapy.http.Request` objects
+ is now named ``encoding``, in line with all other fields (:issue:`5130`)
+
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+- ``scrapy.http.TextResponse.body_as_unicode``, deprecated in Scrapy 2.2, has
+ now been removed. (:issue:`5393`)
+
+- ``scrapy.item.BaseItem``, deprecated in Scrapy 2.2, has now been removed.
+ (:issue:`5398`)
+
+- ``scrapy.item.DictItem``, deprecated in Scrapy 1.8, has now been removed.
+ (:issue:`5398`)
+
+- ``scrapy.Spider.make_requests_from_url``, deprecated in Scrapy 1.4, has now
+ been removed. (:issue:`4178`, :issue:`4356`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+- When a function is assigned to the :setting:`FEED_URI_PARAMS` setting,
+ returning ``None`` or modifying the ``params`` input parameter is now
+ deprecated. Return a new dictionary instead. (:issue:`4962`, :issue:`4966`)
+
+- :mod:`scrapy.utils.reqser` is deprecated. (:issue:`5130`)
+
+ - Instead of :func:`~scrapy.utils.reqser.request_to_dict`, use the new
+ :meth:`Request.to_dict ` method.
+
+ - Instead of :func:`~scrapy.utils.reqser.request_from_dict`, use the new
+ :func:`scrapy.utils.request.request_from_dict` function.
+
+- In :mod:`scrapy.squeues`, the following queue classes are deprecated:
+ :class:`~scrapy.squeues.PickleFifoDiskQueueNonRequest`,
+ :class:`~scrapy.squeues.PickleLifoDiskQueueNonRequest`,
+ :class:`~scrapy.squeues.MarshalFifoDiskQueueNonRequest`,
+ and :class:`~scrapy.squeues.MarshalLifoDiskQueueNonRequest`. You should
+ instead use:
+ :class:`~scrapy.squeues.PickleFifoDiskQueue`,
+ :class:`~scrapy.squeues.PickleLifoDiskQueue`,
+ :class:`~scrapy.squeues.MarshalFifoDiskQueue`,
+ and :class:`~scrapy.squeues.MarshalLifoDiskQueue`. (:issue:`5117`)
+
+- Many aspects of :class:`scrapy.core.engine.ExecutionEngine` that come from
+ a time when this class could handle multiple :class:`~scrapy.Spider`
+ objects at a time have been deprecated. (:issue:`5090`)
+
+ - The :meth:`~scrapy.core.engine.ExecutionEngine.has_capacity` method
+ is deprecated.
+
+ - The :meth:`~scrapy.core.engine.ExecutionEngine.schedule` method is
+ deprecated, use :meth:`~scrapy.core.engine.ExecutionEngine.crawl` or
+ :meth:`~scrapy.core.engine.ExecutionEngine.download` instead.
+
+ - The :attr:`~scrapy.core.engine.ExecutionEngine.open_spiders` attribute
+ is deprecated, use :attr:`~scrapy.core.engine.ExecutionEngine.spider`
+ instead.
+
+ - The ``spider`` parameter is deprecated for the following methods:
+
+ - :meth:`~scrapy.core.engine.ExecutionEngine.spider_is_idle`
+
+ - :meth:`~scrapy.core.engine.ExecutionEngine.crawl`
+
+ - :meth:`~scrapy.core.engine.ExecutionEngine.download`
+
+ Instead, call :meth:`~scrapy.core.engine.ExecutionEngine.open_spider`
+ first to set the :class:`~scrapy.Spider` object.
+
+
+New features
+~~~~~~~~~~~~
+
+- You can now use :ref:`item filtering ` to control which items
+ are exported to each output feed. (:issue:`4575`, :issue:`5178`,
+ :issue:`5161`, :issue:`5203`)
+
+- You can now apply :ref:`post-processing ` to feeds, and
+ :ref:`built-in post-processing plugins ` are provided for
+ output file compression. (:issue:`2174`, :issue:`5168`, :issue:`5190`)
+
+- The :setting:`FEEDS` setting now supports :class:`pathlib.Path` objects as
+ keys. (:issue:`5383`, :issue:`5384`)
+
+- Enabling :ref:`asyncio ` while using Windows and Python 3.8
+ or later will automatically switch the asyncio event loop to one that
+ allows Scrapy to work. See :ref:`asyncio-windows`. (:issue:`4976`,
+ :issue:`5315`)
+
+- The :command:`genspider` command now supports a start URL instead of a
+ domain name. (:issue:`4439`)
+
+- :mod:`scrapy.utils.defer` gained 2 new functions,
+ :func:`~scrapy.utils.defer.deferred_to_future` and
+ :func:`~scrapy.utils.defer.maybe_deferred_to_future`, to help :ref:`await
+ on Deferreds when using the asyncio reactor `.
+ (:issue:`5288`)
+
+- :ref:`Amazon S3 feed export storage ` gained
+ support for `temporary security credentials`_
+ (:setting:`AWS_SESSION_TOKEN`) and endpoint customization
+ (:setting:`AWS_ENDPOINT_URL`). (:issue:`4998`, :issue:`5210`)
+
+ .. _temporary security credentials: https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#temporary-access-keys
+
+- New :setting:`LOG_FILE_APPEND` setting to allow truncating the log file.
+ (:issue:`5279`)
+
+- :attr:`Request.cookies ` values that are
+ :class:`bool`, :class:`float` or :class:`int` are cast to :class:`str`.
+ (:issue:`5252`, :issue:`5253`)
+
+- You may now raise :exc:`~scrapy.exceptions.CloseSpider` from a handler of
+ the :signal:`spider_idle` signal to customize the reason why the spider is
+ stopping. (:issue:`5191`)
+
+- When using
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware`, the
+ proxy URL for non-HTTPS HTTP/1.1 requests no longer needs to include a URL
+ scheme. (:issue:`4505`, :issue:`4649`)
+
+- All built-in queues now expose a ``peek`` method that returns the next
+ queue object (like ``pop``) but does not remove the returned object from
+ the queue. (:issue:`5112`)
+
+ If the underlying queue does not support peeking (e.g. because you are not
+ using ``queuelib`` 1.6.1 or later), the ``peek`` method raises
+ :exc:`NotImplementedError`.
+
+- :class:`~scrapy.http.Request` and :class:`~scrapy.http.Response` now have
+ an ``attributes`` attribute that makes subclassing easier. For
+ :class:`~scrapy.http.Request`, it also allows subclasses to work with
+ :func:`scrapy.utils.request.request_from_dict`. (:issue:`1877`,
+ :issue:`5130`, :issue:`5218`)
+
+- The :meth:`~scrapy.core.scheduler.BaseScheduler.open` and
+ :meth:`~scrapy.core.scheduler.BaseScheduler.close` methods of the
+ :ref:`scheduler ` are now optional. (:issue:`3559`)
+
+- HTTP/1.1 :exc:`~scrapy.core.downloader.handlers.http11.TunnelError`
+ exceptions now only truncate response bodies longer than 1000 characters,
+ instead of those longer than 32 characters, making it easier to debug such
+ errors. (:issue:`4881`, :issue:`5007`)
+
+- :class:`~scrapy.loader.ItemLoader` now supports non-text responses.
+ (:issue:`5145`, :issue:`5269`)
+
+
+Bug fixes
+~~~~~~~~~
+
+- The :setting:`TWISTED_REACTOR` and :setting:`ASYNCIO_EVENT_LOOP` settings
+ are no longer ignored if defined in :attr:`~scrapy.Spider.custom_settings`.
+ (:issue:`4485`, :issue:`5352`)
+
+- Removed a module-level Twisted reactor import that could prevent
+ :ref:`using the asyncio reactor `. (:issue:`5357`)
+
+- The :command:`startproject` command works with existing folders again.
+ (:issue:`4665`, :issue:`4676`)
+
+- The :setting:`FEED_URI_PARAMS` setting now behaves as documented.
+ (:issue:`4962`, :issue:`4966`)
+
+- :attr:`Request.cb_kwargs ` once again allows the
+ ``callback`` keyword. (:issue:`5237`, :issue:`5251`, :issue:`5264`)
+
+- Made :func:`scrapy.utils.response.open_in_browser` support more complex
+ HTML. (:issue:`5319`, :issue:`5320`)
+
+- Fixed :attr:`CSVFeedSpider.quotechar
+ ` being interpreted as the CSV file
+ encoding. (:issue:`5391`, :issue:`5394`)
+
+- Added missing setuptools_ to the list of dependencies. (:issue:`5122`)
+
+ .. _setuptools: https://pypi.org/project/setuptools/
+
+- :class:`LinkExtractor `
+ now also works as expected with links that have comma-separated ``rel``
+ attribute values including ``nofollow``. (:issue:`5225`)
+
+- Fixed a :exc:`TypeError` that could be raised during :ref:`feed export
+ ` parameter parsing. (:issue:`5359`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+- :ref:`asyncio support ` is no longer considered
+ experimental. (:issue:`5332`)
+
+- Included :ref:`Windows-specific help for asyncio usage `.
+ (:issue:`4976`, :issue:`5315`)
+
+- Rewrote :ref:`topics-headless-browsing` with up-to-date best practices.
+ (:issue:`4484`, :issue:`4613`)
+
+- Documented :ref:`local file naming in media pipelines
+ `. (:issue:`5069`, :issue:`5152`)
+
+- :ref:`faq` now covers spider file name collision issues. (:issue:`2680`,
+ :issue:`3669`)
+
+- Provided better context and instructions to disable the
+ :setting:`URLLENGTH_LIMIT` setting. (:issue:`5135`, :issue:`5250`)
+
+- Documented that :ref:`reppy-parser` does not support Python 3.9+.
+ (:issue:`5226`, :issue:`5231`)
+
+- Documented :ref:`the scheduler component `.
+ (:issue:`3537`, :issue:`3559`)
+
+- Documented the method used by :ref:`media pipelines
+ ` to :ref:`determine if a file has expired
+ `. (:issue:`5120`, :issue:`5254`)
+
+- :ref:`run-multiple-spiders` now features
+ :func:`scrapy.utils.project.get_project_settings` usage. (:issue:`5070`)
+
+- :ref:`run-multiple-spiders` now covers what happens when you define
+ different per-spider values for some settings that cannot differ at run
+ time. (:issue:`4485`, :issue:`5352`)
+
+- Extended the documentation of the
+ :class:`~scrapy.extensions.statsmailer.StatsMailer` extension.
+ (:issue:`5199`, :issue:`5217`)
+
+- Added :setting:`JOBDIR` to :ref:`topics-settings`. (:issue:`5173`,
+ :issue:`5224`)
+
+- Documented :attr:`Spider.attribute `.
+ (:issue:`5174`, :issue:`5244`)
+
+- Documented :attr:`TextResponse.urljoin `.
+ (:issue:`1582`)
+
+- Added the ``body_length`` parameter to the documented signature of the
+ :signal:`headers_received` signal. (:issue:`5270`)
+
+- Clarified :meth:`SelectorList.get ` usage
+ in the :ref:`tutorial `. (:issue:`5256`)
+
+- The documentation now features the shortest import path of classes with
+ multiple import paths. (:issue:`2733`, :issue:`5099`)
+
+- ``quotes.toscrape.com`` references now use HTTPS instead of HTTP.
+ (:issue:`5395`, :issue:`5396`)
+
+- Added a link to `our Discord server `_
+ to :ref:`getting-help`. (:issue:`5421`, :issue:`5422`)
+
+- The pronunciation of the project name is now :ref:`officially
+ ` /ˈskreɪpaɪ/. (:issue:`5280`, :issue:`5281`)
+
+- Added the Scrapy logo to the README. (:issue:`5255`, :issue:`5258`)
+
+- Fixed issues and implemented minor improvements. (:issue:`3155`,
+ :issue:`4335`, :issue:`5074`, :issue:`5098`, :issue:`5134`, :issue:`5180`,
+ :issue:`5194`, :issue:`5239`, :issue:`5266`, :issue:`5271`, :issue:`5273`,
+ :issue:`5274`, :issue:`5276`, :issue:`5347`, :issue:`5356`, :issue:`5414`,
+ :issue:`5415`, :issue:`5416`, :issue:`5419`, :issue:`5420`)
+
+
+Quality Assurance
+~~~~~~~~~~~~~~~~~
+
+- Added support for Python 3.10. (:issue:`5212`, :issue:`5221`,
+ :issue:`5265`)
+
+- Significantly reduced memory usage by
+ :func:`scrapy.utils.response.response_httprepr`, used by the
+ :class:`~scrapy.downloadermiddlewares.stats.DownloaderStats` downloader
+ middleware, which is enabled by default. (:issue:`4964`, :issue:`4972`)
+
+- Removed uses of the deprecated :mod:`optparse` module. (:issue:`5366`,
+ :issue:`5374`)
+
+- Extended typing hints. (:issue:`5077`, :issue:`5090`, :issue:`5100`,
+ :issue:`5108`, :issue:`5171`, :issue:`5215`, :issue:`5334`)
+
+- Improved tests, fixed CI issues, removed unused code. (:issue:`5094`,
+ :issue:`5157`, :issue:`5162`, :issue:`5198`, :issue:`5207`, :issue:`5208`,
+ :issue:`5229`, :issue:`5298`, :issue:`5299`, :issue:`5310`, :issue:`5316`,
+ :issue:`5333`, :issue:`5388`, :issue:`5389`, :issue:`5400`, :issue:`5401`,
+ :issue:`5404`, :issue:`5405`, :issue:`5407`, :issue:`5410`, :issue:`5412`,
+ :issue:`5425`, :issue:`5427`)
+
+- Implemented improvements for contributors. (:issue:`5080`, :issue:`5082`,
+ :issue:`5177`, :issue:`5200`)
+
+- Implemented cleanups. (:issue:`5095`, :issue:`5106`, :issue:`5209`,
+ :issue:`5228`, :issue:`5235`, :issue:`5245`, :issue:`5246`, :issue:`5292`,
+ :issue:`5314`, :issue:`5322`)
+
+
+.. _release-2.5.1:
+
+Scrapy 2.5.1 (2021-10-05)
+-------------------------
+
+* **Security bug fix:**
+
+ If you use
+ :class:`~scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware`
+ (i.e. the ``http_user`` and ``http_pass`` spider attributes) for HTTP
+ authentication, any request exposes your credentials to the request target.
+
+ To prevent unintended exposure of authentication credentials to unintended
+ domains, you must now additionally set a new, additional spider attribute,
+ ``http_auth_domain``, and point it to the specific domain to which the
+ authentication credentials must be sent.
+
+ If the ``http_auth_domain`` spider attribute is not set, the domain of the
+ first request will be considered the HTTP authentication target, and
+ authentication credentials will only be sent in requests targeting that
+ domain.
+
+ If you need to send the same HTTP authentication credentials to multiple
+ domains, you can use :func:`w3lib.http.basic_auth_header` instead to
+ set the value of the ``Authorization`` header of your requests.
+
+ If you *really* want your spider to send the same HTTP authentication
+ credentials to any domain, set the ``http_auth_domain`` spider attribute
+ to ``None``.
+
+ Finally, if you are a user of `scrapy-splash`_, know that this version of
+ Scrapy breaks compatibility with scrapy-splash 0.7.2 and earlier. You will
+ need to upgrade scrapy-splash to a greater version for it to continue to
+ work.
+
+.. _scrapy-splash: https://github.com/scrapy-plugins/scrapy-splash
+
+
+.. _release-2.5.0:
+
+Scrapy 2.5.0 (2021-04-06)
+-------------------------
+
+Highlights:
+
+- Official Python 3.9 support
+
+- Experimental :ref:`HTTP/2 support `
+
+- New :func:`~scrapy.downloadermiddlewares.retry.get_retry_request` function
+ to retry requests from spider callbacks
+
+- New :class:`~scrapy.signals.headers_received` signal that allows stopping
+ downloads early
+
+- New :class:`Response.protocol ` attribute
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+- Removed all code that :ref:`was deprecated in 1.7.0 <1.7-deprecations>` and
+ had not :ref:`already been removed in 2.4.0 <2.4-deprecation-removals>`.
+ (:issue:`4901`)
+
+- Removed support for the ``SCRAPY_PICKLED_SETTINGS_TO_OVERRIDE`` environment
+ variable, :ref:`deprecated in 1.8.0 <1.8-deprecations>`. (:issue:`4912`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+- The :mod:`scrapy.utils.py36` module is now deprecated in favor of
+ :mod:`scrapy.utils.asyncgen`. (:issue:`4900`)
+
+
+New features
+~~~~~~~~~~~~
+
+- Experimental :ref:`HTTP/2 support ` through a new download handler
+ that can be assigned to the ``https`` protocol in the
+ :setting:`DOWNLOAD_HANDLERS` setting.
+ (:issue:`1854`, :issue:`4769`, :issue:`5058`, :issue:`5059`, :issue:`5066`)
+
+- The new :func:`scrapy.downloadermiddlewares.retry.get_retry_request`
+ function may be used from spider callbacks or middlewares to handle the
+ retrying of a request beyond the scenarios that
+ :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware` supports.
+ (:issue:`3590`, :issue:`3685`, :issue:`4902`)
+
+- The new :class:`~scrapy.signals.headers_received` signal gives early access
+ to response headers and allows :ref:`stopping downloads
+ `.
+ (:issue:`1772`, :issue:`4897`)
+
+- The new :attr:`Response.protocol `
+ attribute gives access to the string that identifies the protocol used to
+ download a response. (:issue:`4878`)
+
+- :ref:`Stats ` now include the following entries that indicate
+ the number of successes and failures in storing
+ :ref:`feeds `::
+
+ feedexport/success_count/
+ feedexport/failed_count/
+
+ Where ```` is the feed storage backend class name, such as
+ :class:`~scrapy.extensions.feedexport.FileFeedStorage` or
+ :class:`~scrapy.extensions.feedexport.FTPFeedStorage`.
+
+ (:issue:`3947`, :issue:`4850`)
+
+- The :class:`~scrapy.spidermiddlewares.urllength.UrlLengthMiddleware` spider
+ middleware now logs ignored URLs with ``INFO`` :ref:`logging level
+ ` instead of ``DEBUG``, and it now includes the following entry
+ into :ref:`stats ` to keep track of the number of ignored
+ URLs::
+
+ urllength/request_ignored_count
+
+ (:issue:`5036`)
+
+- The
+ :class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`
+ downloader middleware now logs the number of decompressed responses and the
+ total count of resulting bytes::
+
+ httpcompression/response_bytes
+ httpcompression/response_count
+
+ (:issue:`4797`, :issue:`4799`)
+
+
+Bug fixes
+~~~~~~~~~
+
+- Fixed installation on PyPy installing PyDispatcher in addition to
+ PyPyDispatcher, which could prevent Scrapy from working depending on which
+ package got imported. (:issue:`4710`, :issue:`4814`)
+
+- When inspecting a callback to check if it is a generator that also returns
+ a value, an exception is no longer raised if the callback has a docstring
+ with lower indentation than the following code.
+ (:issue:`4477`, :issue:`4935`)
+
+- The `Content-Length `_
+ header is no longer omitted from responses when using the default, HTTP/1.1
+ download handler (see :setting:`DOWNLOAD_HANDLERS`).
+ (:issue:`5009`, :issue:`5034`, :issue:`5045`, :issue:`5057`, :issue:`5062`)
+
+- Setting the :reqmeta:`handle_httpstatus_all` request meta key to ``False``
+ now has the same effect as not setting it at all, instead of having the
+ same effect as setting it to ``True``.
+ (:issue:`3851`, :issue:`4694`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+- Added instructions to :ref:`install Scrapy in Windows using pip
+ `.
+ (:issue:`4715`, :issue:`4736`)
+
+- Logging documentation now includes :ref:`additional ways to filter logs
+ `.
+ (:issue:`4216`, :issue:`4257`, :issue:`4965`)
+
+- Covered how to deal with long lists of allowed domains in the :ref:`FAQ
+ `. (:issue:`2263`, :issue:`3667`)
+
+- Covered scrapy-bench_ in :ref:`benchmarking`.
+ (:issue:`4996`, :issue:`5016`)
+
+- Clarified that one :ref:`extension ` instance is created
+ per crawler.
+ (:issue:`5014`)
+
+- Fixed some errors in examples.
+ (:issue:`4829`, :issue:`4830`, :issue:`4907`, :issue:`4909`,
+ :issue:`5008`)
+
+- Fixed some external links, typos, and so on.
+ (:issue:`4892`, :issue:`4899`, :issue:`4936`, :issue:`4942`, :issue:`5005`,
+ :issue:`5063`)
+
+- The :ref:`list of Request.meta keys ` is now sorted
+ alphabetically.
+ (:issue:`5061`, :issue:`5065`)
+
+- Updated references to Scrapinghub, which is now called Zyte.
+ (:issue:`4973`, :issue:`5072`)
+
+- Added a mention to contributors in the README. (:issue:`4956`)
+
+- Reduced the top margin of lists. (:issue:`4974`)
+
+
+Quality Assurance
+~~~~~~~~~~~~~~~~~
+
+- Made Python 3.9 support official (:issue:`4757`, :issue:`4759`)
+
+- Extended typing hints (:issue:`4895`)
+
+- Fixed deprecated uses of the Twisted API.
+ (:issue:`4940`, :issue:`4950`, :issue:`5073`)
+
+- Made our tests run with the new pip resolver.
+ (:issue:`4710`, :issue:`4814`)
+
+- Added tests to ensure that :ref:`coroutine support `
+ is tested. (:issue:`4987`)
+
+- Migrated from Travis CI to GitHub Actions. (:issue:`4924`)
+
+- Fixed CI issues.
+ (:issue:`4986`, :issue:`5020`, :issue:`5022`, :issue:`5027`, :issue:`5052`,
+ :issue:`5053`)
+
+- Implemented code refactorings, style fixes and cleanups.
+ (:issue:`4911`, :issue:`4982`, :issue:`5001`, :issue:`5002`, :issue:`5076`)
+
+
+.. _release-2.4.1:
+
+Scrapy 2.4.1 (2020-11-17)
+-------------------------
+
+- Fixed :ref:`feed exports ` overwrite support (:issue:`4845`, :issue:`4857`, :issue:`4859`)
+
+- Fixed the AsyncIO event loop handling, which could make code hang
+ (:issue:`4855`, :issue:`4872`)
+
+- Fixed the IPv6-capable DNS resolver
+ :class:`~scrapy.resolver.CachingHostnameResolver` for download handlers
+ that call
+ :meth:`reactor.resolve `
+ (:issue:`4802`, :issue:`4803`)
+
+- Fixed the output of the :command:`genspider` command showing placeholders
+ instead of the import path of the generated spider module (:issue:`4874`)
+
+- Migrated Windows CI from Azure Pipelines to GitHub Actions (:issue:`4869`,
+ :issue:`4876`)
+
+
+.. _release-2.4.0:
+
+Scrapy 2.4.0 (2020-10-11)
+-------------------------
+
+Highlights:
+
+* Python 3.5 support has been dropped.
+
+* The ``file_path`` method of :ref:`media pipelines `
+ can now access the source :ref:`item `.
+
+ This allows you to set a download file path based on item data.
+
+* The new ``item_export_kwargs`` key of the :setting:`FEEDS` setting allows
+ to define keyword parameters to pass to :ref:`item exporter classes
+ `
+
+* You can now choose whether :ref:`feed exports `
+ overwrite or append to the output file.
+
+ For example, when using the :command:`crawl` or :command:`runspider`
+ commands, you can use the ``-O`` option instead of ``-o`` to overwrite the
+ output file.
+
+* Zstd-compressed responses are now supported if zstandard_ is installed.
+
+* In settings, where the import path of a class is required, it is now
+ possible to pass a class object instead.
+
+Modified requirements
+~~~~~~~~~~~~~~~~~~~~~
+
+* Python 3.6 or greater is now required; support for Python 3.5 has been
+ dropped
+
+ As a result:
+
+ - When using PyPy, PyPy 7.2.0 or greater :ref:`is now required
+ `
+
+ - For Amazon S3 storage support in :ref:`feed exports
+ ` or :ref:`media pipelines
+ `, botocore_ 1.4.87 or greater is now required
+
+ - To use the :ref:`images pipeline `, Pillow_ 4.0.0 or
+ greater is now required
+
+ (:issue:`4718`, :issue:`4732`, :issue:`4733`, :issue:`4742`, :issue:`4743`,
+ :issue:`4764`)
+
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+* :class:`~scrapy.downloadermiddlewares.cookies.CookiesMiddleware` once again
+ discards cookies defined in :attr:`Request.headers
+ `.
+
+ We decided to revert this bug fix, introduced in Scrapy 2.2.0, because it
+ was reported that the current implementation could break existing code.
+
+ If you need to set cookies for a request, use the :class:`Request.cookies
+ ` parameter.
+
+ A future version of Scrapy will include a new, better implementation of the
+ reverted bug fix.
+
+ (:issue:`4717`, :issue:`4823`)
+
+
+.. _2.4-deprecation-removals:
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+* :class:`scrapy.extensions.feedexport.S3FeedStorage` no longer reads the
+ values of ``access_key`` and ``secret_key`` from the running project
+ settings when they are not passed to its ``__init__`` method; you must
+ either pass those parameters to its ``__init__`` method or use
+ :class:`S3FeedStorage.from_crawler
+ `
+ (:issue:`4356`, :issue:`4411`, :issue:`4688`)
+
+* :attr:`Rule.process_request `
+ no longer admits callables which expect a single ``request`` parameter,
+ rather than both ``request`` and ``response`` (:issue:`4818`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+* In custom :ref:`media pipelines `, signatures that
+ do not accept a keyword-only ``item`` parameter in any of the methods that
+ :ref:`now support this parameter ` are now
+ deprecated (:issue:`4628`, :issue:`4686`)
+
+* In custom :ref:`feed storage backend classes `,
+ ``__init__`` method signatures that do not accept a keyword-only
+ ``feed_options`` parameter are now deprecated (:issue:`547`, :issue:`716`,
+ :issue:`4512`)
+
+* The :class:`scrapy.utils.python.WeakKeyCache` class is now deprecated
+ (:issue:`4684`, :issue:`4701`)
+
+* The :func:`scrapy.utils.boto.is_botocore` function is now deprecated, use
+ :func:`scrapy.utils.boto.is_botocore_available` instead (:issue:`4734`,
+ :issue:`4776`)
+
+
+New features
+~~~~~~~~~~~~
+
+.. _media-pipeline-item-parameter:
+
+* The following methods of :ref:`media pipelines ` now
+ accept an ``item`` keyword-only parameter containing the source
+ :ref:`item `:
+
+ - In :class:`scrapy.pipelines.files.FilesPipeline`:
+
+ - :meth:`~scrapy.pipelines.files.FilesPipeline.file_downloaded`
+
+ - :meth:`~scrapy.pipelines.files.FilesPipeline.file_path`
+
+ - :meth:`~scrapy.pipelines.files.FilesPipeline.media_downloaded`
+
+ - :meth:`~scrapy.pipelines.files.FilesPipeline.media_to_download`
+
+ - In :class:`scrapy.pipelines.images.ImagesPipeline`:
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.file_downloaded`
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.file_path`
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.get_images`
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.image_downloaded`
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.media_downloaded`
+
+ - :meth:`~scrapy.pipelines.images.ImagesPipeline.media_to_download`
+
+ (:issue:`4628`, :issue:`4686`)
+
+* The new ``item_export_kwargs`` key of the :setting:`FEEDS` setting allows
+ to define keyword parameters to pass to :ref:`item exporter classes
+ ` (:issue:`4606`, :issue:`4768`)
+
+* :ref:`Feed exports ` gained overwrite support:
+
+ * When using the :command:`crawl` or :command:`runspider` commands, you
+ can use the ``-O`` option instead of ``-o`` to overwrite the output
+ file
+
+ * You can use the ``overwrite`` key in the :setting:`FEEDS` setting to
+ configure whether to overwrite the output file (``True``) or append to
+ its content (``False``)
+
+ * The ``__init__`` and ``from_crawler`` methods of :ref:`feed storage
+ backend classes ` now receive a new keyword-only
+ parameter, ``feed_options``, which is a dictionary of :ref:`feed
+ options `
+
+ (:issue:`547`, :issue:`716`, :issue:`4512`)
+
+* Zstd-compressed responses are now supported if zstandard_ is installed
+ (:issue:`4831`)
+
+* In settings, where the import path of a class is required, it is now
+ possible to pass a class object instead (:issue:`3870`, :issue:`3873`).
+
+ This includes also settings where only part of its value is made of an
+ import path, such as :setting:`DOWNLOADER_MIDDLEWARES` or
+ :setting:`DOWNLOAD_HANDLERS`.
+
+* :ref:`Downloader middlewares ` can now
+ override :class:`response.request `.
+
+ If a :ref:`downloader middleware ` returns
+ a :class:`~scrapy.http.Response` object from
+ :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_response`
+ or
+ :meth:`~scrapy.downloadermiddlewares.DownloaderMiddleware.process_exception`
+ with a custom :class:`~scrapy.http.Request` object assigned to
+ :class:`response.request `:
+
+ - The response is handled by the callback of that custom
+ :class:`~scrapy.http.Request` object, instead of being handled by the
+ callback of the original :class:`~scrapy.http.Request` object
+
+ - That custom :class:`~scrapy.http.Request` object is now sent as the
+ ``request`` argument to the :signal:`response_received` signal, instead
+ of the original :class:`~scrapy.http.Request` object
+
+ (:issue:`4529`, :issue:`4632`)
+
+* When using the :ref:`FTP feed storage backend `:
+
+ - It is now possible to set the new ``overwrite`` :ref:`feed option
+ ` to ``False`` to append to an existing file instead of
+ overwriting it
+
+ - The FTP password can now be omitted if it is not necessary
+
+ (:issue:`547`, :issue:`716`, :issue:`4512`)
+
+* The ``__init__`` method of :class:`~scrapy.exporters.CsvItemExporter` now
+ supports an ``errors`` parameter to indicate how to handle encoding errors
+ (:issue:`4755`)
+
+* When :ref:`using asyncio `, it is now possible to
+ :ref:`set a custom asyncio loop ` (:issue:`4306`,
+ :issue:`4414`)
+
+* Serialized requests (see :ref:`topics-jobs`) now support callbacks that are
+ spider methods that delegate on other callable (:issue:`4756`)
+
+* When a response is larger than :setting:`DOWNLOAD_MAXSIZE`, the logged
+ message is now a warning, instead of an error (:issue:`3874`,
+ :issue:`3886`, :issue:`4752`)
+
+
+Bug fixes
+~~~~~~~~~
+
+* The :command:`genspider` command no longer overwrites existing files
+ unless the ``--force`` option is used (:issue:`4561`, :issue:`4616`,
+ :issue:`4623`)
+
+* Cookies with an empty value are no longer considered invalid cookies
+ (:issue:`4772`)
+
+* The :command:`runspider` command now supports files with the ``.pyw`` file
+ extension (:issue:`4643`, :issue:`4646`)
+
+* The :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware`
+ middleware now simply ignores unsupported proxy values (:issue:`3331`,
+ :issue:`4778`)
+
+* Checks for generator callbacks with a ``return`` statement no longer warn
+ about ``return`` statements in nested functions (:issue:`4720`,
+ :issue:`4721`)
+
+* The system file mode creation mask no longer affects the permissions of
+ files generated using the :command:`startproject` command (:issue:`4722`)
+
+* :func:`scrapy.utils.iterators.xmliter` now supports namespaced node names
+ (:issue:`861`, :issue:`4746`)
+
+* :class:`~scrapy.Request` objects can now have ``about:`` URLs, which can
+ work when using a headless browser (:issue:`4835`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+* The :setting:`FEED_URI_PARAMS` setting is now documented (:issue:`4671`,
+ :issue:`4724`)
+
+* Improved the documentation of
+ :ref:`link extractors ` with an usage example from
+ a spider callback and reference documentation for the
+ :class:`~scrapy.link.Link` class (:issue:`4751`, :issue:`4775`)
+
+* Clarified the impact of :setting:`CONCURRENT_REQUESTS` when using the
+ :class:`~scrapy.extensions.closespider.CloseSpider` extension
+ (:issue:`4836`)
+
+* Removed references to Python 2’s ``unicode`` type (:issue:`4547`,
+ :issue:`4703`)
+
+* We now have an :ref:`official deprecation policy `
+ (:issue:`4705`)
+
+* Our :ref:`documentation policies ` now cover usage
+ of Sphinx’s :rst:dir:`versionadded` and :rst:dir:`versionchanged`
+ directives, and we have removed usages referencing Scrapy 1.4.0 and earlier
+ versions (:issue:`3971`, :issue:`4310`)
+
+* Other documentation cleanups (:issue:`4090`, :issue:`4782`, :issue:`4800`,
+ :issue:`4801`, :issue:`4809`, :issue:`4816`, :issue:`4825`)
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+* Extended typing hints (:issue:`4243`, :issue:`4691`)
+
+* Added tests for the :command:`check` command (:issue:`4663`)
+
+* Fixed test failures on Debian (:issue:`4726`, :issue:`4727`, :issue:`4735`)
+
+* Improved Windows test coverage (:issue:`4723`)
+
+* Switched to :ref:`formatted string literals ` where possible
+ (:issue:`4307`, :issue:`4324`, :issue:`4672`)
+
+* Modernized :func:`super` usage (:issue:`4707`)
+
+* Other code and test cleanups (:issue:`1790`, :issue:`3288`, :issue:`4165`,
+ :issue:`4564`, :issue:`4651`, :issue:`4714`, :issue:`4738`, :issue:`4745`,
+ :issue:`4747`, :issue:`4761`, :issue:`4765`, :issue:`4804`, :issue:`4817`,
+ :issue:`4820`, :issue:`4822`, :issue:`4839`)
+
+
.. _release-2.3.0:
Scrapy 2.3.0 (2020-08-04)
@@ -427,9 +2359,8 @@ Bug fixes
* zope.interface 5.0.0 and later versions are now supported
(:issue:`4447`, :issue:`4448`)
-* :meth:`Spider.make_requests_from_url
- `, deprecated in Scrapy
- 1.4.0, now issues a warning when used (:issue:`4412`)
+* ``Spider.make_requests_from_url``, deprecated in Scrapy 1.4.0, now issues a
+ warning when used (:issue:`4412`)
Documentation
@@ -687,7 +2618,7 @@ New features
:issue:`4370`)
* A new ``keep_fragments`` parameter of
- :func:`scrapy.utils.request.request_fingerprint` allows to generate
+ ``scrapy.utils.request.request_fingerprint`` allows to generate
different fingerprints for requests with different fragments in their URL
(:issue:`4104`)
@@ -941,6 +2872,141 @@ affect subclasses:
(:issue:`3884`)
+.. _release-1.8.3:
+
+Scrapy 1.8.3 (2022-07-25)
+-------------------------
+
+**Security bug fix:**
+
+- When :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware`
+ processes a request with :reqmeta:`proxy` metadata, and that
+ :reqmeta:`proxy` metadata includes proxy credentials,
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` sets
+ the ``Proxy-Authorization`` header, but only if that header is not already
+ set.
+
+ There are third-party proxy-rotation downloader middlewares that set
+ different :reqmeta:`proxy` metadata every time they process a request.
+
+ Because of request retries and redirects, the same request can be processed
+ by downloader middlewares more than once, including both
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` and
+ any third-party proxy-rotation downloader middleware.
+
+ These third-party proxy-rotation downloader middlewares could change the
+ :reqmeta:`proxy` metadata of a request to a new value, but fail to remove
+ the ``Proxy-Authorization`` header from the previous value of the
+ :reqmeta:`proxy` metadata, causing the credentials of one proxy to be sent
+ to a different proxy.
+
+ To prevent the unintended leaking of proxy credentials, the behavior of
+ :class:`~scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware` is now
+ as follows when processing a request:
+
+ - If the request being processed defines :reqmeta:`proxy` metadata that
+ includes credentials, the ``Proxy-Authorization`` header is always
+ updated to feature those credentials.
+
+ - If the request being processed defines :reqmeta:`proxy` metadata
+ without credentials, the ``Proxy-Authorization`` header is removed
+ *unless* it was originally defined for the same proxy URL.
+
+ To remove proxy credentials while keeping the same proxy URL, remove
+ the ``Proxy-Authorization`` header.
+
+ - If the request has no :reqmeta:`proxy` metadata, or that metadata is a
+ falsy value (e.g. ``None``), the ``Proxy-Authorization`` header is
+ removed.
+
+ It is no longer possible to set a proxy URL through the
+ :reqmeta:`proxy` metadata but set the credentials through the
+ ``Proxy-Authorization`` header. Set proxy credentials through the
+ :reqmeta:`proxy` metadata instead.
+
+
+.. _release-1.8.2:
+
+Scrapy 1.8.2 (2022-03-01)
+-------------------------
+
+**Security bug fixes:**
+
+- When a :class:`~scrapy.http.Request` object with cookies defined gets a
+ redirect response causing a new :class:`~scrapy.http.Request` object to be
+ scheduled, the cookies defined in the original
+ :class:`~scrapy.http.Request` object are no longer copied into the new
+ :class:`~scrapy.http.Request` object.
+
+ If you manually set the ``Cookie`` header on a
+ :class:`~scrapy.http.Request` object and the domain name of the redirect
+ URL is not an exact match for the domain of the URL of the original
+ :class:`~scrapy.http.Request` object, your ``Cookie`` header is now dropped
+ from the new :class:`~scrapy.http.Request` object.
+
+ The old behavior could be exploited by an attacker to gain access to your
+ cookies. Please, see the `cjvr-mfj7-j4j8 security advisory`_ for more
+ information.
+
+ .. _cjvr-mfj7-j4j8 security advisory: https://github.com/scrapy/scrapy/security/advisories/GHSA-cjvr-mfj7-j4j8
+
+ .. note:: It is still possible to enable the sharing of cookies between
+ different domains with a shared domain suffix (e.g.
+ ``example.com`` and any subdomain) by defining the shared domain
+ suffix (e.g. ``example.com``) as the cookie domain when defining
+ your cookies. See the documentation of the
+ :class:`~scrapy.http.Request` class for more information.
+
+- When the domain of a cookie, either received in the ``Set-Cookie`` header
+ of a response or defined in a :class:`~scrapy.http.Request` object, is set
+ to a `public suffix `_, the cookie is now
+ ignored unless the cookie domain is the same as the request domain.
+
+ The old behavior could be exploited by an attacker to inject cookies into
+ your requests to some other domains. Please, see the `mfjm-vh54-3f96
+ security advisory`_ for more information.
+
+ .. _mfjm-vh54-3f96 security advisory: https://github.com/scrapy/scrapy/security/advisories/GHSA-mfjm-vh54-3f96
+
+
+.. _release-1.8.1:
+
+Scrapy 1.8.1 (2021-10-05)
+-------------------------
+
+* **Security bug fix:**
+
+ If you use
+ :class:`~scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware`
+ (i.e. the ``http_user`` and ``http_pass`` spider attributes) for HTTP
+ authentication, any request exposes your credentials to the request target.
+
+ To prevent unintended exposure of authentication credentials to unintended
+ domains, you must now additionally set a new, additional spider attribute,
+ ``http_auth_domain``, and point it to the specific domain to which the
+ authentication credentials must be sent.
+
+ If the ``http_auth_domain`` spider attribute is not set, the domain of the
+ first request will be considered the HTTP authentication target, and
+ authentication credentials will only be sent in requests targeting that
+ domain.
+
+ If you need to send the same HTTP authentication credentials to multiple
+ domains, you can use :func:`w3lib.http.basic_auth_header` instead to
+ set the value of the ``Authorization`` header of your requests.
+
+ If you *really* want your spider to send the same HTTP authentication
+ credentials to any domain, set the ``http_auth_domain`` spider attribute
+ to ``None``.
+
+ Finally, if you are a user of `scrapy-splash`_, know that this version of
+ Scrapy breaks compatibility with scrapy-splash 0.7.2 and earlier. You will
+ need to upgrade scrapy-splash to a greater version for it to continue to
+ work.
+
+.. _scrapy-splash: https://github.com/scrapy-plugins/scrapy-splash
+
+
.. _release-1.8.0:
Scrapy 1.8.0 (2019-10-28)
@@ -984,11 +3050,13 @@ Backward-incompatible changes
* :class:`~scrapy.loader.ItemLoader` now turns the values of its input item
into lists:
- >>> item = MyItem()
- >>> item['field'] = 'value1'
- >>> loader = ItemLoader(item=item)
- >>> item['field']
- ['value1']
+ .. code-block:: pycon
+
+ >>> item = MyItem()
+ >>> item["field"] = "value1"
+ >>> loader = ItemLoader(item=item)
+ >>> item["field"]
+ ['value1']
This is needed to allow adding values to existing fields
(``loader.add_value('field', 'value2')``).
@@ -1106,6 +3174,8 @@ Deprecation removals
* ``scrapy.xlib`` has been removed (:issue:`4015`)
+.. _1.8-deprecations:
+
Deprecations
~~~~~~~~~~~~
@@ -1239,7 +3309,7 @@ New features
* A new scheduler priority queue,
``scrapy.pqueues.DownloaderAwarePriorityQueue``, may be
:ref:`enabled ` for a significant
- scheduling improvement on crawls targetting multiple web domains, at the
+ scheduling improvement on crawls targeting multiple web domains, at the
cost of no :setting:`CONCURRENT_REQUESTS_PER_IP` support (:issue:`3520`)
* A new :attr:`Request.cb_kwargs ` attribute
@@ -1462,6 +3532,8 @@ The following deprecated settings have also been removed (:issue:`3578`):
* ``SPIDER_MANAGER_CLASS`` (use :setting:`SPIDER_LOADER_CLASS`)
+.. _1.7-deprecations:
+
Deprecations
~~~~~~~~~~~~
@@ -1943,7 +4015,7 @@ New Features
~~~~~~~~~~~~
- Accept proxy credentials in :reqmeta:`proxy` request meta key (:issue:`2526`)
-- Support `brotli`_-compressed content; requires optional `brotlipy`_
+- Support `brotli-compressed`_ content; requires optional `brotlipy`_
(:issue:`2535`)
- New :ref:`response.follow ` shortcut
for creating requests (:issue:`1940`)
@@ -1980,7 +4052,7 @@ New Features
- ``python -m scrapy`` as a more explicit alternative to ``scrapy`` command
(:issue:`2740`)
-.. _brotli: https://github.com/google/brotli
+.. _brotli-compressed: https://www.ietf.org/rfc/rfc7932.txt
.. _brotlipy: https://github.com/python-hyper/brotlipy/
Bug fixes
@@ -2101,7 +4173,7 @@ Bug fixes
- Fix compatibility with Twisted 17+ (:issue:`2496`, :issue:`2528`).
- Fix ``scrapy.Item`` inheritance on Python 3.6 (:issue:`2511`).
- Enforce numeric values for components order in ``SPIDER_MIDDLEWARES``,
- ``DOWNLOADER_MIDDLEWARES``, ``EXTENIONS`` and ``SPIDER_CONTRACTS`` (:issue:`2420`).
+ ``DOWNLOADER_MIDDLEWARES``, ``EXTENSIONS`` and ``SPIDER_CONTRACTS`` (:issue:`2420`).
Documentation
~~~~~~~~~~~~~
@@ -2275,7 +4347,7 @@ Bug fixes
- Fix for selected callbacks when using ``CrawlSpider`` with :command:`scrapy parse `
(:issue:`2225`).
- Fix for invalid JSON and XML files when spider yields no items (:issue:`872`).
-- Implement ``flush()`` fpr ``StreamLogger`` avoiding a warning in logs (:issue:`2125`).
+- Implement ``flush()`` for ``StreamLogger`` avoiding a warning in logs (:issue:`2125`).
Refactoring
~~~~~~~~~~~
@@ -2562,8 +4634,6 @@ Relocations
+ Note: telnet is not enabled on Python 3
(https://github.com/scrapy/scrapy/pull/1524#issuecomment-146985595)
-.. _parsel: https://github.com/scrapy/parsel
-
Bugfixes
~~~~~~~~
@@ -3138,7 +5208,7 @@ Scrapy 0.24.3 (2014-08-09)
- adding some xpath tips to selectors docs (:commit:`2d103e0`)
- fix tests to account for https://github.com/scrapy/w3lib/pull/23 (:commit:`f8d366a`)
- get_func_args maximum recursion fix #728 (:commit:`81344ea`)
-- Updated input/ouput processor example according to #560. (:commit:`f7c4ea8`)
+- Updated input/output processor example according to #560. (:commit:`f7c4ea8`)
- Fixed Python syntax in tutorial. (:commit:`db59ed9`)
- Add test case for tunneling proxy (:commit:`f090260`)
- Bugfix for leaking Proxy-Authorization header to remote host when using tunneling (:commit:`d8793af`)
@@ -3263,7 +5333,7 @@ Scrapy 0.22.1 (released 2014-02-08)
- BaseSgmlLinkExtractor: Added unit test of a link with an inner tag (:commit:`c1cb418`)
- BaseSgmlLinkExtractor: Fixed unknown_endtag() so that it only set current_link=None when the end tag match the opening tag (:commit:`7e4d627`)
- Fix tests for Travis-CI build (:commit:`76c7e20`)
-- replace unencodable codepoints with html entities. fixes #562 and #285 (:commit:`5f87b17`)
+- replace unencodeable codepoints with html entities. fixes #562 and #285 (:commit:`5f87b17`)
- RegexLinkExtractor: encode URL unicode value when creating Links (:commit:`d0ee545`)
- Updated the tutorial crawl output with latest output. (:commit:`8da65de`)
- Updated shell docs with the crawler reference and fixed the actual shell output. (:commit:`875b9ab`)
@@ -3288,7 +5358,7 @@ Enhancements
- [**Backward incompatible**] Switched HTTPCacheMiddleware backend to filesystem (:issue:`541`)
To restore old backend set ``HTTPCACHE_STORAGE`` to ``scrapy.contrib.httpcache.DbmCacheStorage``
- Proxy \https:// urls using CONNECT method (:issue:`392`, :issue:`397`)
-- Add a middleware to crawl ajax crawleable pages as defined by google (:issue:`343`)
+- Add a middleware to crawl ajax crawlable pages as defined by google (:issue:`343`)
- Rename scrapy.spider.BaseSpider to scrapy.spider.Spider (:issue:`510`, :issue:`519`)
- Selectors register EXSLT namespaces by default (:issue:`472`)
- Unify item loaders similar to selectors renaming (:issue:`461`)
@@ -3468,7 +5538,7 @@ Scrapy 0.18.0 (released 2013-08-09)
-----------------------------------
- Lot of improvements to testsuite run using Tox, including a way to test on pypi
-- Handle GET parameters for AJAX crawleable urls (:commit:`3fe2a32`)
+- Handle GET parameters for AJAX crawlable urls (:commit:`3fe2a32`)
- Use lxml recover option to parse sitemaps (:issue:`347`)
- Bugfix cookie merging by hostname and not by netloc (:issue:`352`)
- Support disabling ``HttpCompressionMiddleware`` using a flag setting (:issue:`359`)
@@ -3502,8 +5572,8 @@ Scrapy 0.18.0 (released 2013-08-09)
- Added ``--pdb`` option to ``scrapy`` command line tool
- Added :meth:`XPathSelector.remove_namespaces ` which allows to remove all namespaces from XML documents for convenience (to work with namespace-less XPaths). Documented in :ref:`topics-selectors`.
- Several improvements to spider contracts
-- New default middleware named MetaRefreshMiddldeware that handles meta-refresh html tag redirections,
-- MetaRefreshMiddldeware and RedirectMiddleware have different priorities to address #62
+- New default middleware named MetaRefreshMiddleware that handles meta-refresh html tag redirections,
+- MetaRefreshMiddleware and RedirectMiddleware have different priorities to address #62
- added from_crawler method to spiders
- added system tests with mock server
- more improvements to macOS compatibility (thanks Alex Cepoi)
@@ -3645,7 +5715,7 @@ Scrapy changes:
- promoted :ref:`topics-djangoitem` to main contrib
- LogFormatter method now return dicts(instead of strings) to support lazy formatting (:issue:`164`, :commit:`dcef7b0`)
- downloader handlers (:setting:`DOWNLOAD_HANDLERS` setting) now receive settings as the first argument of the ``__init__`` method
-- replaced memory usage acounting with (more portable) `resource`_ module, removed ``scrapy.utils.memory`` module
+- replaced memory usage accounting with (more portable) `resource`_ module, removed ``scrapy.utils.memory`` module
- removed signal: ``scrapy.mail.mail_sent``
- removed ``TRACK_REFS`` setting, now :ref:`trackrefs ` is always enabled
- DBM is now the default storage backend for HTTP cache middleware
@@ -3711,7 +5781,7 @@ Scrapy 0.14
New features and settings
~~~~~~~~~~~~~~~~~~~~~~~~~
-- Support for `AJAX crawleable urls`_
+- Support for `AJAX crawlable urls`_
- New persistent scheduler that stores requests on disk, allowing to suspend and resume crawls (:rev:`2737`)
- added ``-o`` option to ``scrapy crawl``, a shortcut for dumping scraped items into a file (or standard output using ``-``)
- Added support for passing custom settings to Scrapyd ``schedule.json`` api (:rev:`2779`, :rev:`2783`)
@@ -3765,7 +5835,7 @@ Code rearranged and removed
- Removed googledir project from ``examples/googledir``. There's now a new example project called ``dirbot`` available on GitHub: https://github.com/scrapy/dirbot
- Removed support for default field values in Scrapy items (:rev:`2616`)
- Removed experimental crawlspider v2 (:rev:`2632`)
-- Removed scheduler middleware to simplify architecture. Duplicates filter is now done in the scheduler itself, using the same dupe fltering class as before (``DUPEFILTER_CLASS`` setting) (:rev:`2640`)
+- Removed scheduler middleware to simplify architecture. Duplicates filter is now done in the scheduler itself, using the same dupe filtering class as before (``DUPEFILTER_CLASS`` setting) (:rev:`2640`)
- Removed support for passing urls to ``scrapy crawl`` command (use ``scrapy parse`` instead) (:rev:`2704`)
- Removed deprecated Execution Queue (:rev:`2704`)
- Removed (undocumented) spider context extension (from scrapy.contrib.spidercontext) (:rev:`2780`)
@@ -3800,7 +5870,7 @@ Scrapyd changes
~~~~~~~~~~~~~~~
- Scrapyd now uses one process per spider
-- It stores one log file per spider run, and rotate them keeping the lastest 5 logs per spider (by default)
+- It stores one log file per spider run, and rotate them keeping the latest 5 logs per spider (by default)
- A minimal web ui was added, available at http://localhost:6800 by default
- There is now a ``scrapy server`` command to start a Scrapyd server of the current project
@@ -3836,7 +5906,7 @@ New features and improvements
- Added two new methods to item pipeline open_spider(), close_spider() with deferred support (#195)
- Support for overriding default request headers per spider (#181)
- Replaced default Spider Manager with one with similar functionality but not depending on Twisted Plugins (#186)
-- Splitted Debian package into two packages - the library and the service (#187)
+- Split Debian package into two packages - the library and the service (#187)
- Scrapy log refactoring (#188)
- New extension for keeping persistent spider contexts among different runs (#203)
- Added ``dont_redirect`` request.meta key for avoiding redirects (#233)
@@ -3857,7 +5927,7 @@ API changes
- ``url`` and ``body`` attributes of Request objects are now read-only (#230)
- ``Request.copy()`` and ``Request.replace()`` now also copies their ``callback`` and ``errback`` attributes (#231)
- Removed ``UrlFilterMiddleware`` from ``scrapy.contrib`` (already disabled by default)
-- Offsite middelware doesn't filter out any request coming from a spider that doesn't have a allowed_domains attribute (#225)
+- Offsite middleware doesn't filter out any request coming from a spider that doesn't have a allowed_domains attribute (#225)
- Removed Spider Manager ``load()`` method. Now spiders are loaded in the ``__init__`` method itself.
- Changes to Scrapy Manager (now called "Crawler"):
- ``scrapy.core.manager.ScrapyManager`` class renamed to ``scrapy.crawler.Crawler``
@@ -3971,7 +6041,7 @@ Backward-incompatible changes
- Renamed setting: ``REQUESTS_PER_DOMAIN`` to ``CONCURRENT_REQUESTS_PER_SPIDER`` (:rev:`1830`, :rev:`1844`)
- Renamed setting: ``CONCURRENT_DOMAINS`` to ``CONCURRENT_SPIDERS`` (:rev:`1830`)
- Refactored HTTP Cache middleware
-- HTTP Cache middleware has been heavilty refactored, retaining the same functionality except for the domain sectorization which was removed. (:rev:`1843` )
+- HTTP Cache middleware has been heavily refactored, retaining the same functionality except for the domain sectorization which was removed. (:rev:`1843` )
- Renamed exception: ``DontCloseDomain`` to ``DontCloseSpider`` (:rev:`1859` | #120)
- Renamed extension: ``DelayedCloseDomain`` to ``SpiderCloseDelay`` (:rev:`1861` | #121)
- Removed obsolete ``scrapy.utils.markup.remove_escape_chars`` function - use ``scrapy.utils.markup.replace_escape_chars`` instead (:rev:`1865`)
@@ -3982,7 +6052,8 @@ Scrapy 0.7
First release of Scrapy.
-.. _AJAX crawleable urls: https://developers.google.com/search/docs/ajax-crawling/docs/getting-started?csw=1
+.. _AJAX crawlable urls: https://developers.google.com/search/docs/ajax-crawling/docs/getting-started?csw=1
+.. _boto3: https://github.com/boto/boto3
.. _botocore: https://github.com/boto/botocore
.. _chunked transfer encoding: https://en.wikipedia.org/wiki/Chunked_transfer_encoding
.. _ClientForm: http://wwwsearch.sourceforge.net/old/ClientForm/
@@ -3993,6 +6064,7 @@ First release of Scrapy.
.. _LevelDB: https://github.com/google/leveldb
.. _lxml: https://lxml.de/
.. _marshal: https://docs.python.org/2/library/marshal.html
+.. _parsel: https://github.com/scrapy/parsel
.. _parsel.csstranslator.GenericTranslator: https://parsel.readthedocs.io/en/latest/parsel.html#parsel.csstranslator.GenericTranslator
.. _parsel.csstranslator.HTMLTranslator: https://parsel.readthedocs.io/en/latest/parsel.html#parsel.csstranslator.HTMLTranslator
.. _parsel.csstranslator.XPathExpr: https://parsel.readthedocs.io/en/latest/parsel.html#parsel.csstranslator.XPathExpr
@@ -4004,13 +6076,14 @@ First release of Scrapy.
.. _resource: https://docs.python.org/2/library/resource.html
.. _robots.txt: https://www.robotstxt.org/
.. _scrapely: https://github.com/scrapy/scrapely
+.. _scrapy-bench: https://github.com/scrapy/scrapy-bench
.. _service_identity: https://service-identity.readthedocs.io/en/stable/
.. _six: https://six.readthedocs.io/
.. _tox: https://pypi.org/project/tox/
.. _Twisted: https://twistedmatrix.com/trac/
-.. _Twisted - hello, asynchronous programming: http://jessenoller.com/blog/2009/02/11/twisted-hello-asynchronous-programming/
.. _w3lib: https://github.com/scrapy/w3lib
.. _w3lib.encoding: https://github.com/scrapy/w3lib/blob/master/w3lib/encoding.py
.. _What is cacheable: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1
.. _zope.interface: https://zopeinterface.readthedocs.io/en/latest/
.. _Zsh: https://www.zsh.org/
+.. _zstandard: https://pypi.org/project/zstandard/
diff --git a/docs/requirements.txt b/docs/requirements.txt
index 3d34b47da..9f9aef711 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -1,4 +1,4 @@
-Sphinx>=3.0
-sphinx-hoverxref>=0.2b1
-sphinx-notfound-page>=0.4
-sphinx_rtd_theme>=0.4
+sphinx==5.0.2
+sphinx-hoverxref==1.1.1
+sphinx-notfound-page==0.8
+sphinx-rtd-theme==1.0.0
diff --git a/docs/topics/addons.rst b/docs/topics/addons.rst
new file mode 100644
index 000000000..1bf2172bd
--- /dev/null
+++ b/docs/topics/addons.rst
@@ -0,0 +1,193 @@
+.. _topics-addons:
+
+=======
+Add-ons
+=======
+
+Scrapy's add-on system is a framework which unifies managing and configuring
+components that extend Scrapy's core functionality, such as middlewares,
+extensions, or pipelines. It provides users with a plug-and-play experience in
+Scrapy extension management, and grants extensive configuration control to
+developers.
+
+
+Activating and configuring add-ons
+==================================
+
+During :class:`~scrapy.crawler.Crawler` initialization, the list of enabled
+add-ons is read from your ``ADDONS`` setting.
+
+The ``ADDONS`` setting is a dict in which every key is an add-on class or its
+import path and the value is its priority.
+
+This is an example where two add-ons are enabled in a project's
+``settings.py``::
+
+ ADDONS = {
+ 'path.to.someaddon': 0,
+ SomeAddonClass: 1,
+ }
+
+
+Writing your own add-ons
+========================
+
+Add-ons are Python classes that include the following method:
+
+.. method:: update_settings(settings)
+
+ This method is called during the initialization of the
+ :class:`~scrapy.crawler.Crawler`. Here, you should perform dependency checks
+ (e.g. for external Python libraries) and update the
+ :class:`~scrapy.settings.Settings` object as wished, e.g. enable components
+ for this add-on or set required configuration of other extensions.
+
+ :param settings: The settings object storing Scrapy/component configuration
+ :type settings: :class:`~scrapy.settings.Settings`
+
+They can also have the following method:
+
+.. classmethod:: from_crawler(cls, crawler)
+ :noindex:
+
+ If present, this class method is called to create an add-on instance
+ from a :class:`~scrapy.crawler.Crawler`. It must return a new instance
+ of the add-on. The crawler object provides access to all Scrapy core
+ components like settings and signals; it is a way for the add-on to access
+ them and hook its functionality into Scrapy.
+
+ :param crawler: The crawler that uses this add-on
+ :type crawler: :class:`~scrapy.crawler.Crawler`
+
+The settings set by the add-on should use the ``addon`` priority (see
+:ref:`populating-settings` and :func:`scrapy.settings.BaseSettings.set`)::
+
+ class MyAddon:
+ def update_settings(self, settings):
+ settings.set("DNSCACHE_ENABLED", True, "addon")
+
+This allows users to override these settings in the project or spider
+configuration. This is not possible with settings that are mutable objects,
+such as the dict that is a value of :setting:`ITEM_PIPELINES`. In these cases
+you can provide an add-on-specific setting that governs whether the add-on will
+modify :setting:`ITEM_PIPELINES`::
+
+ class MyAddon:
+ def update_settings(self, settings):
+ if settings.getbool("MYADDON_ENABLE_PIPELINE"):
+ settings["ITEM_PIPELINES"]["path.to.mypipeline"] = 200
+
+If the ``update_settings`` method raises
+:exc:`scrapy.exceptions.NotConfigured`, the add-on will be skipped. This makes
+it easy to enable an add-on only when some conditions are met.
+
+Fallbacks
+---------
+
+Some components provided by add-ons need to fall back to "default"
+implementations, e.g. a custom download handler needs to send the request that
+it doesn't handle via the default download handler, or a stats collector that
+includes some additional processing but otherwise uses the default stats
+collector. And it's possible that a project needs to use several custom
+components of the same type, e.g. two custom download handlers that support
+different kinds of custom requests and still need to use the default download
+handler for other requests. To make such use cases easier to configure, we
+recommend that such custom components should be written in the following way:
+
+1. The custom component (e.g. ``MyDownloadHandler``) shouldn't inherit from the
+ default Scrapy one (e.g.
+ ``scrapy.core.downloader.handlers.http.HTTPDownloadHandler``), but instead
+ be able to load the class of the fallback component from a special setting
+ (e.g. ``MY_FALLBACK_DOWNLOAD_HANDLER``), create an instance of it and use
+ it.
+2. The add-ons that include these components should read the current value of
+ the default setting (e.g. ``DOWNLOAD_HANDLERS``) in their
+ ``update_settings()`` methods, save that value into the fallback setting
+ (``MY_FALLBACK_DOWNLOAD_HANDLER`` mentioned earlier) and set the default
+ setting to the component provided by the add-on (e.g.
+ ``MyDownloadHandler``). If the fallback setting is already set by the user,
+ they shouldn't change it.
+3. This way, if there are several add-ons that want to modify the same setting,
+ all of them will fallback to the component from the previous one and then to
+ the Scrapy default. The order of that depends on the priority order in the
+ ``ADDONS`` setting.
+
+
+Add-on examples
+===============
+
+Set some basic configuration:
+
+.. code-block:: python
+
+ class MyAddon:
+ def update_settings(self, settings):
+ settings["ITEM_PIPELINES"]["path.to.mypipeline"] = 200
+ settings.set("DNSCACHE_ENABLED", True, "addon")
+
+Check dependencies:
+
+.. code-block:: python
+
+ class MyAddon:
+ def update_settings(self, settings):
+ try:
+ import boto
+ except ImportError:
+ raise NotConfigured("MyAddon requires the boto library")
+ ...
+
+Access the crawler instance:
+
+.. code-block:: python
+
+ class MyAddon:
+ def __init__(self, crawler) -> None:
+ super().__init__()
+ self.crawler = crawler
+
+ @classmethod
+ def from_crawler(cls, crawler):
+ return cls(crawler)
+
+ def update_settings(self, settings):
+ ...
+
+Use a fallback component:
+
+.. code-block:: python
+
+ from scrapy.core.downloader.handlers.http import HTTPDownloadHandler
+
+
+ FALLBACK_SETTING = "MY_FALLBACK_DOWNLOAD_HANDLER"
+
+
+ class MyHandler:
+ lazy = False
+
+ def __init__(self, settings, crawler):
+ dhcls = load_object(settings.get(FALLBACK_SETTING))
+ self._fallback_handler = create_instance(
+ dhcls,
+ settings=None,
+ crawler=crawler,
+ )
+
+ def download_request(self, request, spider):
+ if request.meta.get("my_params"):
+ # handle the request
+ ...
+ else:
+ return self._fallback_handler.download_request(request, spider)
+
+
+ class MyAddon:
+ def update_settings(self, settings):
+ if not settings.get(FALLBACK_SETTING):
+ settings.set(
+ FALLBACK_SETTING,
+ settings.getwithbase("DOWNLOAD_HANDLERS")["https"],
+ "addon",
+ )
+ settings["DOWNLOAD_HANDLERS"]["https"] = MyHandler
diff --git a/docs/topics/api.rst b/docs/topics/api.rst
index 445b2979f..175c877de 100644
--- a/docs/topics/api.rst
+++ b/docs/topics/api.rst
@@ -29,9 +29,16 @@ how you :ref:`configure the downloader middlewares
.. class:: Crawler(spidercls, settings)
The Crawler object must be instantiated with a
- :class:`scrapy.spiders.Spider` subclass and a
+ :class:`scrapy.Spider` subclass and a
:class:`scrapy.settings.Settings` object.
+ .. attribute:: request_fingerprinter
+
+ The request fingerprint builder of this crawler.
+
+ This is used from extensions and middlewares to build short, unique
+ identifiers for requests. See :ref:`request-fingerprints`.
+
.. attribute:: settings
The settings manager of this crawler.
@@ -93,7 +100,7 @@ how you :ref:`configure the downloader middlewares
Starts the crawler by instantiating its spider class with the given
``args`` and ``kwargs`` arguments, while setting the execution engine in
- motion.
+ motion. Should be called only once.
Returns a deferred that is fired when the crawl is finished.
@@ -125,16 +132,15 @@ Settings API
precedence over lesser ones when setting and retrieving values in the
:class:`~scrapy.settings.Settings` class.
- .. highlight:: python
-
- ::
+ .. code-block:: python
SETTINGS_PRIORITIES = {
- 'default': 0,
- 'command': 10,
- 'project': 20,
- 'spider': 30,
- 'cmdline': 40,
+ "default": 0,
+ "command": 10,
+ "addon": 15,
+ "project": 20,
+ "spider": 30,
+ "cmdline": 40,
}
For a detailed explanation on each settings sources, see:
@@ -196,7 +202,7 @@ SpiderLoader API
match the request's url against the domains of the spiders.
:param request: queried request
- :type request: :class:`~scrapy.http.Request` instance
+ :type request: :class:`~scrapy.Request` instance
.. _topics-api-signals:
diff --git a/docs/topics/architecture.rst b/docs/topics/architecture.rst
index 074c59241..0c3a7ed88 100644
--- a/docs/topics/architecture.rst
+++ b/docs/topics/architecture.rst
@@ -67,7 +67,7 @@ this:
the :ref:`Scheduler ` and asks for possible next Requests
to crawl.
-9. The process repeats (from step 1) until there are no more requests from the
+9. The process repeats (from step 3) until there are no more requests from the
:ref:`Scheduler `.
Components
@@ -87,8 +87,9 @@ of the system, and triggering events when certain actions occur. See the
Scheduler
---------
-The Scheduler receives requests from the engine and enqueues them for feeding
-them later (also to the engine) when the engine requests them.
+The :ref:`scheduler ` receives requests from the engine and
+enqueues them for feeding them later (also to the engine) when the engine
+requests them.
.. _component-downloader:
diff --git a/docs/topics/asyncio.rst b/docs/topics/asyncio.rst
index bfb430d52..07baea071 100644
--- a/docs/topics/asyncio.rst
+++ b/docs/topics/asyncio.rst
@@ -1,16 +1,15 @@
+.. _using-asyncio:
+
=======
asyncio
=======
.. versionadded:: 2.0
-Scrapy has partial support :mod:`asyncio`. After you :ref:`install the asyncio
-reactor `, you may use :mod:`asyncio` and
+Scrapy has partial support for :mod:`asyncio`. After you :ref:`install the
+asyncio reactor `, you may use :mod:`asyncio` and
:mod:`asyncio`-powered libraries in any :doc:`coroutine `.
-.. warning:: :mod:`asyncio` support in Scrapy is experimental. Future Scrapy
- versions may introduce related changes without a deprecation
- period or warning.
.. _install-asyncio:
@@ -27,14 +26,121 @@ reactor manually. You can do that using
install_reactor('twisted.internet.asyncioreactor.AsyncioSelectorReactor')
+
+.. _asyncio-preinstalled-reactor:
+
+Handling a pre-installed reactor
+================================
+
+``twisted.internet.reactor`` and some other Twisted imports install the default
+Twisted reactor as a side effect. Once a Twisted reactor is installed, it is
+not possible to switch to a different reactor at run time.
+
+If you :ref:`configure the asyncio Twisted reactor ` and, at
+run time, Scrapy complains that a different reactor is already installed,
+chances are you have some such imports in your code.
+
+You can usually fix the issue by moving those offending module-level Twisted
+imports to the method or function definitions where they are used. For example,
+if you have something like:
+
+.. code-block:: python
+
+ from twisted.internet import reactor
+
+
+ def my_function():
+ reactor.callLater(...)
+
+Switch to something like:
+
+.. code-block:: python
+
+ def my_function():
+ from twisted.internet import reactor
+
+ reactor.callLater(...)
+
+Alternatively, you can try to :ref:`manually install the asyncio reactor
+`, with :func:`~scrapy.utils.reactor.install_reactor`, before
+those imports happen.
+
+
+.. _asyncio-await-dfd:
+
+Awaiting on Deferreds
+=====================
+
+When the asyncio reactor isn't installed, you can await on Deferreds in the
+coroutines directly. When it is installed, this is not possible anymore, due to
+specifics of the Scrapy coroutine integration (the coroutines are wrapped into
+:class:`asyncio.Future` objects, not into
+:class:`~twisted.internet.defer.Deferred` directly), and you need to wrap them into
+Futures. Scrapy provides two helpers for this:
+
+.. autofunction:: scrapy.utils.defer.deferred_to_future
+.. autofunction:: scrapy.utils.defer.maybe_deferred_to_future
+.. tip:: If you need to use these functions in code that aims to be compatible
+ with lower versions of Scrapy that do not provide these functions,
+ down to Scrapy 2.0 (earlier versions do not support
+ :mod:`asyncio`), you can copy the implementation of these functions
+ into your own code.
+
+
+.. _enforce-asyncio-requirement:
+
+Enforcing asyncio as a requirement
+==================================
+
+If you are writing a :ref:`component ` that requires asyncio
+to work, use :func:`scrapy.utils.reactor.is_asyncio_reactor_installed` to
+:ref:`enforce it as a requirement `. For
+example:
+
+.. code-block:: python
+
+ from scrapy.utils.reactor import is_asyncio_reactor_installed
+
+
+ class MyComponent:
+ def __init__(self):
+ if not is_asyncio_reactor_installed():
+ raise ValueError(
+ f"{MyComponent.__qualname__} requires the asyncio Twisted "
+ f"reactor. Make sure you have it configured in the "
+ f"TWISTED_REACTOR setting. See the asyncio documentation "
+ f"of Scrapy for more information."
+ )
+
+
+.. _asyncio-windows:
+
+Windows-specific notes
+======================
+
+The Windows implementation of :mod:`asyncio` can use two event loop
+implementations, :class:`~asyncio.ProactorEventLoop` (default) and
+:class:`~asyncio.SelectorEventLoop`. However, only
+:class:`~asyncio.SelectorEventLoop` works with Twisted.
+
+Scrapy changes the event loop class to :class:`~asyncio.SelectorEventLoop`
+automatically when you change the :setting:`TWISTED_REACTOR` setting or call
+:func:`~scrapy.utils.reactor.install_reactor`.
+
+.. note:: Other libraries you use may require
+ :class:`~asyncio.ProactorEventLoop`, e.g. because it supports
+ subprocesses (this is the case with `playwright`_), so you cannot use
+ them together with Scrapy on Windows (but you should be able to use
+ them on WSL or native Linux).
+
+.. _playwright: https://github.com/microsoft/playwright-python
+
+
.. _using-custom-loops:
Using custom asyncio loops
-==========================
+==========================
You can also use custom asyncio event loops with the asyncio reactor. Set the
-:setting:`ASYNCIO_EVENT_LOOP` setting to the import path of the desired event loop class to
-use it instead of the default asyncio event loop.
-
-
-
+:setting:`ASYNCIO_EVENT_LOOP` setting to the import path of the desired event
+loop class to use it instead of the default asyncio event loop.
diff --git a/docs/topics/benchmarking.rst b/docs/topics/benchmarking.rst
index b01a66188..0643df6a6 100644
--- a/docs/topics/benchmarking.rst
+++ b/docs/topics/benchmarking.rst
@@ -81,5 +81,6 @@ follow links, any custom spider you write will probably do more stuff which
results in slower crawl rates. How slower depends on how much your spider does
and how well it's written.
-In the future, more cases will be added to the benchmarking suite to cover
-other common scenarios.
+Use scrapy-bench_ for more complex benchmarking.
+
+.. _scrapy-bench: https://github.com/scrapy/scrapy-bench
\ No newline at end of file
diff --git a/docs/topics/broad-crawls.rst b/docs/topics/broad-crawls.rst
index 63b60312e..8be89feb2 100644
--- a/docs/topics/broad-crawls.rst
+++ b/docs/topics/broad-crawls.rst
@@ -48,9 +48,11 @@ Scrapy’s default scheduler priority queue is ``'scrapy.pqueues.ScrapyPriorityQ
It works best during single-domain crawl. It does not work well with crawling
many different domains in parallel
-To apply the recommended priority queue use::
+To apply the recommended priority queue use:
- SCHEDULER_PRIORITY_QUEUE = 'scrapy.pqueues.DownloaderAwarePriorityQueue'
+.. code-block:: python
+
+ SCHEDULER_PRIORITY_QUEUE = "scrapy.pqueues.DownloaderAwarePriorityQueue"
.. _broad-crawls-concurrency:
@@ -68,10 +70,12 @@ IP (:setting:`CONCURRENT_REQUESTS_PER_IP`).
The default global concurrency limit in Scrapy is not suitable for crawling
many different domains in parallel, so you will want to increase it. How much
-to increase it will depend on how much CPU and memory you crawler will have
+to increase it will depend on how much CPU and memory your crawler will have
available.
-A good starting point is ``100``::
+A good starting point is ``100``:
+
+.. code-block:: python
CONCURRENT_REQUESTS = 100
@@ -92,7 +96,9 @@ hitting DNS resolver timeouts. Possible solution to increase the number of
threads handling DNS queries. The DNS queue will be processed faster speeding
up establishing of connection and crawling overall.
-To increase maximum thread pool size use::
+To increase maximum thread pool size use:
+
+.. code-block:: python
REACTOR_THREADPOOL_MAXSIZE = 20
@@ -114,9 +120,11 @@ should not use ``DEBUG`` log level when preforming large broad crawls in
production. Using ``DEBUG`` level when developing your (broad) crawler may be
fine though.
-To set the log level use::
+To set the log level use:
- LOG_LEVEL = 'INFO'
+.. code-block:: python
+
+ LOG_LEVEL = "INFO"
Disable cookies
===============
@@ -126,7 +134,9 @@ doing broad crawls (search engine crawlers ignore them), and they improve
performance by saving some CPU cycles and reducing the memory footprint of your
Scrapy crawler.
-To disable cookies use::
+To disable cookies use:
+
+.. code-block:: python
COOKIES_ENABLED = False
@@ -138,7 +148,9 @@ when sites causes are very slow (or fail) to respond, thus causing a timeout
error which gets retried many times, unnecessarily, preventing crawler capacity
to be reused for other domains.
-To disable retries use::
+To disable retries use:
+
+.. code-block:: python
RETRY_ENABLED = False
@@ -149,7 +161,9 @@ Unless you are crawling from a very slow connection (which shouldn't be the
case for broad crawls) reduce the download timeout so that stuck requests are
discarded quickly and free up capacity to process the next ones.
-To reduce the download timeout use::
+To reduce the download timeout use:
+
+.. code-block:: python
DOWNLOAD_TIMEOUT = 15
@@ -162,7 +176,9 @@ revisiting the site at a later crawl. This also help to keep the number of
request constant per crawl batch, otherwise redirect loops may cause the
crawler to dedicate too many resources on any specific domain.
-To disable redirects use::
+To disable redirects use:
+
+.. code-block:: python
REDIRECT_ENABLED = False
@@ -179,7 +195,9 @@ Pages can indicate it in two ways:
"main", "index" website pages.
Scrapy handles (1) automatically; to handle (2) enable
-:ref:`AjaxCrawlMiddleware `::
+:ref:`AjaxCrawlMiddleware `:
+
+.. code-block:: python
AJAXCRAWL_ENABLED = True
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst
index 7de5e8121..1d37895c2 100644
--- a/docs/topics/commands.rst
+++ b/docs/topics/commands.rst
@@ -230,10 +230,13 @@ Usage example::
genspider
---------
-* Syntax: ``scrapy genspider [-t template] ``
+* Syntax: ``scrapy genspider [-t template] ``
* Requires project: *no*
-Create a new spider in the current folder or in the current project's ``spiders`` folder, if called from inside a project. The ```` parameter is set as the spider's ``name``, while ```` is used to generate the ``allowed_domains`` and ``start_urls`` spider's attributes.
+.. versionadded:: 2.6.0
+ The ability to pass a URL instead of a domain.
+
+Create a new spider in the current folder or in the current project's ``spiders`` folder, if called from inside a project. The ```` parameter is set as the spider's ``name``, while ```` is used to generate the ``allowed_domains`` and ``start_urls`` spider's attributes.
Usage example::
@@ -265,11 +268,31 @@ crawl
Start crawling using a spider.
+Supported options:
+
+* ``-h, --help``: show a help message and exit
+
+* ``-a NAME=VALUE``: set a spider argument (may be repeated)
+
+* ``--output FILE`` or ``-o FILE``: append scraped items to the end of FILE (use - for stdout), to define format set a colon at the end of the output URI (i.e. ``-o FILE:FORMAT``)
+
+* ``--overwrite-output FILE`` or ``-O FILE``: dump scraped items into FILE, overwriting any existing file, to define format set a colon at the end of the output URI (i.e. ``-O FILE:FORMAT``)
+
+* ``--output-format FORMAT`` or ``-t FORMAT``: deprecated way to define format to use for dumping items, does not work in combination with ``-O``
+
Usage examples::
$ scrapy crawl myspider
[ ... myspider starts crawling ... ]
+ $ scrapy crawl -o myfile:csv myspider
+ [ ... myspider starts crawling and appends the result to the file myfile in csv format ... ]
+
+ $ scrapy crawl -O myfile:json myspider
+ [ ... myspider starts crawling and saves the result in myfile in json format overwriting the original content... ]
+
+ $ scrapy crawl -o myfile -t csv myspider
+ [ ... myspider starts crawling and appends the result to the file myfile in csv format ... ]
.. command:: check
@@ -591,15 +614,13 @@ Example:
.. code-block:: python
- COMMANDS_MODULE = 'mybot.commands'
+ COMMANDS_MODULE = "mybot.commands"
.. _Deploying your project: https://scrapyd.readthedocs.io/en/latest/deploy.html
Register commands via setup.py entry points
-------------------------------------------
-.. note:: This is an experimental feature, use with caution.
-
You can also add Scrapy commands from an external library by adding a
``scrapy.commands`` section in the entry points of the library ``setup.py``
file.
@@ -612,10 +633,11 @@ The following example adds ``my_command`` command:
from setuptools import setup, find_packages
- setup(name='scrapy-mymodule',
- entry_points={
- 'scrapy.commands': [
- 'my_command=my_scrapy_module.commands:MyCommand',
- ],
- },
- )
+ setup(
+ name="scrapy-mymodule",
+ entry_points={
+ "scrapy.commands": [
+ "my_command=my_scrapy_module.commands:MyCommand",
+ ],
+ },
+ )
diff --git a/docs/topics/components.rst b/docs/topics/components.rst
new file mode 100644
index 000000000..478dd9647
--- /dev/null
+++ b/docs/topics/components.rst
@@ -0,0 +1,86 @@
+.. _topics-components:
+
+==========
+Components
+==========
+
+A Scrapy component is any class whose objects are created using
+:func:`scrapy.utils.misc.create_instance`.
+
+That includes the classes that you may assign to the following settings:
+
+- :setting:`DNS_RESOLVER`
+
+- :setting:`DOWNLOAD_HANDLERS`
+
+- :setting:`DOWNLOADER_CLIENTCONTEXTFACTORY`
+
+- :setting:`DOWNLOADER_MIDDLEWARES`
+
+- :setting:`DUPEFILTER_CLASS`
+
+- :setting:`EXTENSIONS`
+
+- :setting:`FEED_EXPORTERS`
+
+- :setting:`FEED_STORAGES`
+
+- :setting:`ITEM_PIPELINES`
+
+- :setting:`SCHEDULER`
+
+- :setting:`SCHEDULER_DISK_QUEUE`
+
+- :setting:`SCHEDULER_MEMORY_QUEUE`
+
+- :setting:`SCHEDULER_PRIORITY_QUEUE`
+
+- :setting:`SPIDER_MIDDLEWARES`
+
+Third-party Scrapy components may also let you define additional Scrapy
+components, usually configurable through :ref:`settings `, to
+modify their behavior.
+
+.. _enforce-component-requirements:
+
+Enforcing component requirements
+================================
+
+Sometimes, your components may only be intended to work under certain
+conditions. For example, they may require a minimum version of Scrapy to work as
+intended, or they may require certain settings to have specific values.
+
+In addition to describing those conditions in the documentation of your
+component, it is a good practice to raise an exception from the ``__init__``
+method of your component if those conditions are not met at run time.
+
+In the case of :ref:`downloader middlewares `,
+:ref:`extensions `, :ref:`item pipelines
+`, and :ref:`spider middlewares
+`, you should raise
+:exc:`scrapy.exceptions.NotConfigured`, passing a description of the issue as a
+parameter to the exception so that it is printed in the logs, for the user to
+see. For other components, feel free to raise whatever other exception feels
+right to you; for example, :exc:`RuntimeError` would make sense for a Scrapy
+version mismatch, while :exc:`ValueError` may be better if the issue is the
+value of a setting.
+
+If your requirement is a minimum Scrapy version, you may use
+:attr:`scrapy.__version__` to enforce your requirement. For example:
+
+.. code-block:: python
+
+ from packaging.version import parse as parse_version
+
+ import scrapy
+
+
+ class MyComponent:
+ def __init__(self):
+ if parse_version(scrapy.__version__) < parse_version("2.7"):
+ raise RuntimeError(
+ f"{MyComponent.__qualname__} requires Scrapy 2.7 or "
+ f"later, which allow defining the process_spider_output "
+ f"method of spider middlewares as an asynchronous "
+ f"generator."
+ )
diff --git a/docs/topics/contracts.rst b/docs/topics/contracts.rst
index e61421bf1..2d61026e9 100644
--- a/docs/topics/contracts.rst
+++ b/docs/topics/contracts.rst
@@ -11,10 +11,13 @@ integrated way of testing your spiders by the means of contracts.
This allows you to test each callback of your spider by hardcoding a sample url
and check various constraints for how the callback processes the response. Each
contract is prefixed with an ``@`` and included in the docstring. See the
-following example::
+following example:
+
+.. code-block:: python
def parse(self, response):
- """ This function parses a sample response. Some contracts are mingled
+ """
+ This function parses a sample response. Some contracts are mingled
with this docstring.
@url http://www.amazon.com/s?field-keywords=selfish+gene
@@ -37,7 +40,7 @@ This callback is tested using three built-in contracts:
.. class:: CallbackKeywordArgumentsContract
- This contract (``@cb_kwargs``) sets the :attr:`cb_kwargs `
+ This contract (``@cb_kwargs``) sets the :attr:`cb_kwargs `
attribute for the sample request. It must be a valid JSON dictionary.
::
@@ -64,11 +67,13 @@ Custom Contracts
If you find you need more power than the built-in Scrapy contracts you can
create and load your own contracts in the project by using the
-:setting:`SPIDER_CONTRACTS` setting::
+:setting:`SPIDER_CONTRACTS` setting:
+
+.. code-block:: python
SPIDER_CONTRACTS = {
- 'myproject.contracts.ResponseCheck': 10,
- 'myproject.contracts.ItemValidate': 10,
+ "myproject.contracts.ResponseCheck": 10,
+ "myproject.contracts.ItemValidate": 10,
}
Each contract must inherit from :class:`~scrapy.contracts.Contract` and can
@@ -88,7 +93,7 @@ override three methods:
.. method:: Contract.adjust_request_args(args)
This receives a ``dict`` as an argument containing default arguments
- for request object. :class:`~scrapy.http.Request` is used by default,
+ for request object. :class:`~scrapy.Request` is used by default,
but this can be changed with the ``request_cls`` attribute.
If multiple contracts in chain have this attribute defined, the last one is used.
@@ -102,7 +107,7 @@ override three methods:
.. method:: Contract.post_process(output)
This allows processing the output of the callback. Iterators are
- converted listified before being passed to this hook.
+ converted to lists before being passed to this hook.
Raise :class:`~scrapy.exceptions.ContractFail` from
:class:`~scrapy.contracts.Contract.pre_process` or
@@ -111,22 +116,27 @@ Raise :class:`~scrapy.exceptions.ContractFail` from
.. autoclass:: scrapy.exceptions.ContractFail
Here is a demo contract which checks the presence of a custom header in the
-response received::
+response received:
+
+.. skip: next
+.. code-block:: python
from scrapy.contracts import Contract
from scrapy.exceptions import ContractFail
+
class HasHeaderContract(Contract):
- """ Demo contract which checks the presence of a custom header
- @has_header X-CustomHeader
+ """
+ Demo contract which checks the presence of a custom header
+ @has_header X-CustomHeader
"""
- name = 'has_header'
+ name = "has_header"
def pre_process(self, response):
for header in self.args:
if header not in response.headers:
- raise ContractFail('X-CustomHeader not present')
+ raise ContractFail("X-CustomHeader not present")
.. _detecting-contract-check-runs:
@@ -135,14 +145,17 @@ Detecting check runs
When ``scrapy check`` is running, the ``SCRAPY_CHECK`` environment variable is
set to the ``true`` string. You can use :data:`os.environ` to perform any change to
-your spiders or your settings when ``scrapy check`` is used::
+your spiders or your settings when ``scrapy check`` is used:
+
+.. code-block:: python
import os
import scrapy
+
class ExampleSpider(scrapy.Spider):
- name = 'example'
+ name = "example"
def __init__(self):
- if os.environ.get('SCRAPY_CHECK'):
+ if os.environ.get("SCRAPY_CHECK"):
pass # Do some scraper adjustments when a check is running
diff --git a/docs/topics/coroutines.rst b/docs/topics/coroutines.rst
index 3b1549bd3..a65bab3ca 100644
--- a/docs/topics/coroutines.rst
+++ b/docs/topics/coroutines.rst
@@ -1,3 +1,5 @@
+.. _topics-coroutines:
+
==========
Coroutines
==========
@@ -15,16 +17,14 @@ Supported callables
The following callables may be defined as coroutines using ``async def``, and
hence use coroutine syntax (e.g. ``await``, ``async for``, ``async with``):
-- :class:`~scrapy.http.Request` callbacks.
+- :class:`~scrapy.Request` callbacks.
- .. note:: The callback output is not processed until the whole callback
- finishes.
+ If you are using any custom or third-party :ref:`spider middleware
+ `, see :ref:`sync-async-spider-middleware`.
- As a side effect, if the callback raises an exception, none of its
- output is processed.
-
- This is a known caveat of the current implementation that we aim to
- address in a future version of Scrapy.
+ .. versionchanged:: 2.7
+ Output of async callbacks is now processed asynchronously instead of
+ collecting all of it first.
- The :meth:`process_item` method of
:ref:`item pipelines `.
@@ -39,59 +39,88 @@ hence use coroutine syntax (e.g. ``await``, ``async for``, ``async with``):
- :ref:`Signal handlers that support deferreds `.
-Usage
-=====
+- The
+ :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output`
+ method of :ref:`spider middlewares `.
-There are several use cases for coroutines in Scrapy. Code that would
-return Deferreds when written for previous Scrapy versions, such as downloader
-middlewares and signal handlers, can be rewritten to be shorter and cleaner::
+ It must be defined as an :term:`asynchronous generator`. The input
+ ``result`` parameter is an :term:`asynchronous iterable`.
+
+ See also :ref:`sync-async-spider-middleware` and
+ :ref:`universal-spider-middleware`.
+
+ .. versionadded:: 2.7
+
+General usage
+=============
+
+There are several use cases for coroutines in Scrapy.
+
+Code that would return Deferreds when written for previous Scrapy versions,
+such as downloader middlewares and signal handlers, can be rewritten to be
+shorter and cleaner:
+
+.. code-block:: python
from itemadapter import ItemAdapter
+
class DbPipeline:
def _update_item(self, data, item):
adapter = ItemAdapter(item)
- adapter['field'] = data
+ adapter["field"] = data
return item
def process_item(self, item, spider):
adapter = ItemAdapter(item)
- dfd = db.get_some_data(adapter['id'])
+ dfd = db.get_some_data(adapter["id"])
dfd.addCallback(self._update_item, item)
return dfd
-becomes::
+becomes:
+
+.. code-block:: python
from itemadapter import ItemAdapter
+
class DbPipeline:
async def process_item(self, item, spider):
adapter = ItemAdapter(item)
- adapter['field'] = await db.get_some_data(adapter['id'])
+ adapter["field"] = await db.get_some_data(adapter["id"])
return item
Coroutines may be used to call asynchronous code. This includes other
coroutines, functions that return Deferreds and functions that return
:term:`awaitable objects ` such as :class:`~asyncio.Future`.
-This means you can use many useful Python libraries providing such code::
+This means you can use many useful Python libraries providing such code:
- class MySpider(Spider):
+.. skip: next
+.. code-block:: python
+
+ class MySpiderDeferred(Spider):
# ...
- async def parse_with_deferred(self, response):
- additional_response = await treq.get('https://additional.url')
+ async def parse(self, response):
+ additional_response = await treq.get("https://additional.url")
additional_data = await treq.content(additional_response)
# ... use response and additional_data to yield items and requests
- async def parse_with_asyncio(self, response):
+
+ class MySpiderAsyncio(Spider):
+ # ...
+ async def parse(self, response):
async with aiohttp.ClientSession() as session:
- async with session.get('https://additional.url') as additional_response:
- additional_data = await r.text()
+ async with session.get("https://additional.url") as additional_response:
+ additional_data = await additional_response.text()
# ... use response and additional_data to yield items and requests
.. note:: Many libraries that use coroutines, such as `aio-libs`_, require the
:mod:`asyncio` loop and to use them you need to
:doc:`enable asyncio support in Scrapy`.
+.. note:: If you want to ``await`` on Deferreds while using the asyncio reactor,
+ you need to :ref:`wrap them`.
+
Common use cases for asynchronous code include:
* requesting data from websites, databases and other services (in callbacks,
@@ -99,7 +128,159 @@ Common use cases for asynchronous code include:
* storing data in databases (in pipelines and middlewares);
* delaying the spider initialization until some external event (in the
:signal:`spider_opened` handler);
-* calling asynchronous Scrapy methods like ``ExecutionEngine.download`` (see
- :ref:`the screenshot pipeline example`).
+* calling asynchronous Scrapy methods like :meth:`ExecutionEngine.download`
+ (see :ref:`the screenshot pipeline example`).
.. _aio-libs: https://github.com/aio-libs
+
+
+.. _inline-requests:
+
+Inline requests
+===============
+
+The spider below shows how to send a request and await its response all from
+within a spider callback:
+
+.. code-block:: python
+
+ from scrapy import Spider, Request
+ from scrapy.utils.defer import maybe_deferred_to_future
+
+
+ class SingleRequestSpider(Spider):
+ name = "single"
+ start_urls = ["https://example.org/product"]
+
+ async def parse(self, response, **kwargs):
+ additional_request = Request("https://example.org/price")
+ deferred = self.crawler.engine.download(additional_request)
+ additional_response = await maybe_deferred_to_future(deferred)
+ yield {
+ "h1": response.css("h1").get(),
+ "price": additional_response.css("#price").get(),
+ }
+
+You can also send multiple requests in parallel:
+
+.. code-block:: python
+
+ from scrapy import Spider, Request
+ from scrapy.utils.defer import maybe_deferred_to_future
+ from twisted.internet.defer import DeferredList
+
+
+ class MultipleRequestsSpider(Spider):
+ name = "multiple"
+ start_urls = ["https://example.com/product"]
+
+ async def parse(self, response, **kwargs):
+ additional_requests = [
+ Request("https://example.com/price"),
+ Request("https://example.com/color"),
+ ]
+ deferreds = []
+ for r in additional_requests:
+ deferred = self.crawler.engine.download(r)
+ deferreds.append(deferred)
+ responses = await maybe_deferred_to_future(DeferredList(deferreds))
+ yield {
+ "h1": response.css("h1::text").get(),
+ "price": responses[0][1].css(".price::text").get(),
+ "price2": responses[1][1].css(".color::text").get(),
+ }
+
+
+.. _sync-async-spider-middleware:
+
+Mixing synchronous and asynchronous spider middlewares
+======================================================
+
+.. versionadded:: 2.7
+
+The output of a :class:`~scrapy.Request` callback is passed as the ``result``
+parameter to the
+:meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output` method
+of the first :ref:`spider middleware ` from the
+:ref:`list of active spider middlewares `.
+Then the output of that ``process_spider_output`` method is passed to the
+``process_spider_output`` method of the next spider middleware, and so on for
+every active spider middleware.
+
+Scrapy supports mixing :ref:`coroutine methods ` and synchronous methods
+in this chain of calls.
+
+However, if any of the ``process_spider_output`` methods is defined as a
+synchronous method, and the previous ``Request`` callback or
+``process_spider_output`` method is a coroutine, there are some drawbacks to
+the asynchronous-to-synchronous conversion that Scrapy does so that the
+synchronous ``process_spider_output`` method gets a synchronous iterable as its
+``result`` parameter:
+
+- The whole output of the previous ``Request`` callback or
+ ``process_spider_output`` method is awaited at this point.
+
+- If an exception raises while awaiting the output of the previous
+ ``Request`` callback or ``process_spider_output`` method, none of that
+ output will be processed.
+
+ This contrasts with the regular behavior, where all items yielded before
+ an exception raises are processed.
+
+Asynchronous-to-synchronous conversions are supported for backward
+compatibility, but they are deprecated and will stop working in a future
+version of Scrapy.
+
+To avoid asynchronous-to-synchronous conversions, when defining ``Request``
+callbacks as coroutine methods or when using spider middlewares whose
+``process_spider_output`` method is an :term:`asynchronous generator`, all
+active spider middlewares must either have their ``process_spider_output``
+method defined as an asynchronous generator or :ref:`define a
+process_spider_output_async method `.
+
+.. note:: When using third-party spider middlewares that only define a
+ synchronous ``process_spider_output`` method, consider
+ :ref:`making them universal ` through
+ :ref:`subclassing `.
+
+
+.. _universal-spider-middleware:
+
+Universal spider middlewares
+============================
+
+.. versionadded:: 2.7
+
+To allow writing a spider middleware that supports asynchronous execution of
+its ``process_spider_output`` method in Scrapy 2.7 and later (avoiding
+:ref:`asynchronous-to-synchronous conversions `)
+while maintaining support for older Scrapy versions, you may define
+``process_spider_output`` as a synchronous method and define an
+:term:`asynchronous generator` version of that method with an alternative name:
+``process_spider_output_async``.
+
+For example:
+
+.. code-block:: python
+
+ class UniversalSpiderMiddleware:
+ def process_spider_output(self, response, result, spider):
+ for r in result:
+ # ... do something with r
+ yield r
+
+ async def process_spider_output_async(self, response, result, spider):
+ async for r in result:
+ # ... do something with r
+ yield r
+
+.. note:: This is an interim measure to allow, for a time, to write code that
+ works in Scrapy 2.7 and later without requiring
+ asynchronous-to-synchronous conversions, and works in earlier Scrapy
+ versions as well.
+
+ In some future version of Scrapy, however, this feature will be
+ deprecated and, eventually, in a later version of Scrapy, this
+ feature will be removed, and all spider middlewares will be expected
+ to define their ``process_spider_output`` method as an asynchronous
+ generator.
diff --git a/docs/topics/debug.rst b/docs/topics/debug.rst
index d75f17301..49c5b0410 100644
--- a/docs/topics/debug.rst
+++ b/docs/topics/debug.rst
@@ -5,21 +5,25 @@ Debugging Spiders
=================
This document explains the most common techniques for debugging spiders.
-Consider the following Scrapy spider below::
+Consider the following Scrapy spider below:
+
+.. skip: next
+.. code-block:: python
import scrapy
from myproject.items import MyItem
+
class MySpider(scrapy.Spider):
- name = 'myspider'
+ name = "myspider"
start_urls = (
- 'http://example.com/page1',
- 'http://example.com/page2',
- )
+ "http://example.com/page1",
+ "http://example.com/page2",
+ )
def parse(self, response):
#
- # collect `item_urls`
+ # collect `item_urls`
for item_url in item_urls:
yield scrapy.Request(item_url, self.parse_item)
@@ -28,7 +32,9 @@ Consider the following Scrapy spider below::
item = MyItem()
# populate `item` fields
# and extract item_details_url
- yield scrapy.Request(item_details_url, self.parse_details, cb_kwargs={'item': item})
+ yield scrapy.Request(
+ item_details_url, self.parse_details, cb_kwargs={"item": item}
+ )
def parse_details(self, response, item):
# populate more `item` fields
@@ -36,7 +42,7 @@ Consider the following Scrapy spider below::
Basically this is a simple spider which parses two pages of items (the
start_urls). Items also have a details page with additional information, so we
-use the ``cb_kwargs`` functionality of :class:`~scrapy.http.Request` to pass a
+use the ``cb_kwargs`` functionality of :class:`~scrapy.Request` to pass a
partially populated item.
@@ -103,10 +109,13 @@ showing the response received and the output. How to debug the situation when
.. highlight:: python
Fortunately, the :command:`shell` is your bread and butter in this case (see
-:ref:`topics-shell-inspect-response`)::
+:ref:`topics-shell-inspect-response`):
+
+.. code-block:: python
from scrapy.shell import inspect_response
+
def parse_details(self, response, item=None):
if item:
# populate more `item` fields
@@ -121,10 +130,13 @@ Open in browser
Sometimes you just want to see how a certain response looks in a browser, you
can use the ``open_in_browser`` function for that. Here is an example of how
-you would use it::
+you would use it:
+
+.. code-block:: python
from scrapy.utils.response import open_in_browser
+
def parse_details(self, response):
if "item name" not in response.body:
open_in_browser(response)
@@ -138,15 +150,47 @@ Logging
Logging is another useful option for getting information about your spider run.
Although not as convenient, it comes with the advantage that the logs will be
-available in all future runs should they be necessary again::
+available in all future runs should they be necessary again:
+
+.. code-block:: python
def parse_details(self, response, item=None):
if item:
# populate more `item` fields
return item
else:
- self.logger.warning('No item received for %s', response.url)
+ self.logger.warning("No item received for %s", response.url)
For more information, check the :ref:`topics-logging` section.
.. _base tag: https://www.w3schools.com/tags/tag_base.asp
+
+.. _debug-vscode:
+
+Visual Studio Code
+==================
+
+.. highlight:: json
+
+To debug spiders with Visual Studio Code you can use the following ``launch.json``::
+
+ {
+ "version": "0.1.0",
+ "configurations": [
+ {
+ "name": "Python: Launch Scrapy Spider",
+ "type": "python",
+ "request": "launch",
+ "module": "scrapy",
+ "args": [
+ "runspider",
+ "${file}"
+ ],
+ "console": "integratedTerminal"
+ }
+ ]
+ }
+
+
+Also, make sure you enable "User Uncaught Exceptions", to catch exceptions in
+your Scrapy spider.
diff --git a/docs/topics/deploy.rst b/docs/topics/deploy.rst
index 361914a29..961d6dc01 100644
--- a/docs/topics/deploy.rst
+++ b/docs/topics/deploy.rst
@@ -14,7 +14,7 @@ spiders come in.
Popular choices for deploying Scrapy spiders are:
* :ref:`Scrapyd ` (open source)
-* :ref:`Scrapy Cloud ` (cloud-based)
+* :ref:`Zyte Scrapy Cloud ` (cloud-based)
.. _deploy-scrapyd:
@@ -32,28 +32,28 @@ Scrapyd is maintained by some of the Scrapy developers.
.. _deploy-scrapy-cloud:
-Deploying to Scrapy Cloud
-=========================
+Deploying to Zyte Scrapy Cloud
+==============================
-`Scrapy Cloud`_ is a hosted, cloud-based service by `Scrapinghub`_,
-the company behind Scrapy.
+`Zyte Scrapy Cloud`_ is a hosted, cloud-based service by Zyte_, the company
+behind Scrapy.
-Scrapy Cloud removes the need to setup and monitor servers
-and provides a nice UI to manage spiders and review scraped items,
-logs and stats.
+Zyte Scrapy Cloud removes the need to setup and monitor servers and provides a
+nice UI to manage spiders and review scraped items, logs and stats.
-To deploy spiders to Scrapy Cloud you can use the `shub`_ command line tool.
-Please refer to the `Scrapy Cloud documentation`_ for more information.
+To deploy spiders to Zyte Scrapy Cloud you can use the `shub`_ command line
+tool.
+Please refer to the `Zyte Scrapy Cloud documentation`_ for more information.
-Scrapy Cloud is compatible with Scrapyd and one can switch between
+Zyte Scrapy Cloud is compatible with Scrapyd and one can switch between
them as needed - the configuration is read from the ``scrapy.cfg`` file
just like ``scrapyd-deploy``.
-.. _Scrapyd: https://github.com/scrapy/scrapyd
.. _Deploying your project: https://scrapyd.readthedocs.io/en/latest/deploy.html
-.. _Scrapy Cloud: https://scrapinghub.com/scrapy-cloud
+.. _Scrapyd: https://github.com/scrapy/scrapyd
.. _scrapyd-client: https://github.com/scrapy/scrapyd-client
-.. _shub: https://doc.scrapinghub.com/shub.html
.. _scrapyd-deploy documentation: https://scrapyd.readthedocs.io/en/latest/deploy.html
-.. _Scrapy Cloud documentation: https://doc.scrapinghub.com/scrapy-cloud.html
-.. _Scrapinghub: https://scrapinghub.com/
+.. _shub: https://shub.readthedocs.io/en/latest/
+.. _Zyte: https://zyte.com/
+.. _Zyte Scrapy Cloud: https://www.zyte.com/scrapy-cloud/
+.. _Zyte Scrapy Cloud documentation: https://docs.zyte.com/scrapy-cloud.html
diff --git a/docs/topics/developer-tools.rst b/docs/topics/developer-tools.rst
index c83b1a9d9..a15ee1059 100644
--- a/docs/topics/developer-tools.rst
+++ b/docs/topics/developer-tools.rst
@@ -19,14 +19,14 @@ Caveats with inspecting the live browser DOM
Since Developer Tools operate on a live browser DOM, what you'll actually see
when inspecting the page source is not the original HTML, but a modified one
-after applying some browser clean up and executing Javascript code. Firefox,
+after applying some browser clean up and executing JavaScript code. Firefox,
in particular, is known for adding ```` elements to tables. Scrapy, on
the other hand, does not modify the original page HTML, so you won't be able to
extract any data if you use `` `` in your XPath expressions.
Therefore, you should keep in mind the following things:
-* Disable Javascript while inspecting the DOM looking for XPaths to be
+* Disable JavaScript while inspecting the DOM looking for XPaths to be
used in Scrapy (in the Developer Tools settings click `Disable JavaScript`)
* Never use full XPath paths, use relative and clever ones based on attributes
@@ -81,21 +81,23 @@ clicking directly on the tag. If we expand the ``span`` tag with the ``class=
"text"`` we will see the quote-text we clicked on. The `Inspector` lets you
copy XPaths to selected elements. Let's try it out.
-First open the Scrapy shell at http://quotes.toscrape.com/ in a terminal:
+First open the Scrapy shell at https://quotes.toscrape.com/ in a terminal:
.. code-block:: none
- $ scrapy shell "http://quotes.toscrape.com/"
+ $ scrapy shell "https://quotes.toscrape.com/"
Then, back to your web browser, right-click on the ``span`` tag, select
``Copy > XPath`` and paste it in the Scrapy shell like so:
.. invisible-code-block: python
- response = load_response('http://quotes.toscrape.com/', 'quotes.html')
+ response = load_response('https://quotes.toscrape.com/', 'quotes.html')
->>> response.xpath('/html/body/div/div[2]/div[1]/div[1]/span[1]/text()').getall()
-['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”']
+.. code-block:: pycon
+
+ >>> response.xpath("/html/body/div/div[2]/div[1]/div[1]/span[1]/text()").getall()
+ ['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”']
Adding ``text()`` at the end we are able to extract the first quote with this
basic selector. But this XPath is not really that clever. All it does is
@@ -124,11 +126,13 @@ With this knowledge we can refine our XPath: Instead of a path to follow,
we'll simply select all ``span`` tags with the ``class="text"`` by using
the `has-class-extension`_:
->>> response.xpath('//span[has-class("text")]/text()').getall()
-['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”',
-'“It is our choices, Harry, that show what we truly are, far more than our abilities.”',
-'“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”',
-...]
+.. code-block:: pycon
+
+ >>> response.xpath('//span[has-class("text")]/text()').getall()
+ ['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”',
+ '“It is our choices, Harry, that show what we truly are, far more than our abilities.”',
+ '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”',
+ ...]
And with one simple, cleverer XPath we are able to extract all quotes from
the page. We could have constructed a loop over our first XPath to increase
@@ -227,7 +231,7 @@ interests us is the one request called ``quotes?page=1`` with the
type ``json``.
If we click on this request, we see that the request URL is
-``http://quotes.toscrape.com/api/quotes?page=1`` and the response
+``https://quotes.toscrape.com/api/quotes?page=1`` and the response
is a JSON-object that contains our quotes. We can also right-click
on the request and open ``Open in new tab`` to get a better overview.
@@ -237,17 +241,19 @@ on the request and open ``Open in new tab`` to get a better overview.
:alt: JSON-object returned from the quotes.toscrape API
With this response we can now easily parse the JSON-object and
-also request each page to get every quote on the site::
+also request each page to get every quote on the site:
+
+.. code-block:: python
import scrapy
import json
class QuoteSpider(scrapy.Spider):
- name = 'quote'
- allowed_domains = ['quotes.toscrape.com']
+ name = "quote"
+ allowed_domains = ["quotes.toscrape.com"]
page = 1
- start_urls = ['http://quotes.toscrape.com/api/quotes?page=1']
+ start_urls = ["https://quotes.toscrape.com/api/quotes?page=1"]
def parse(self, response):
data = json.loads(response.text)
@@ -255,7 +261,7 @@ also request each page to get every quote on the site::
yield {"quote": quote["text"]}
if data["has_next"]:
self.page += 1
- url = f"http://quotes.toscrape.com/api/quotes?page={self.page}"
+ url = f"https://quotes.toscrape.com/api/quotes?page={self.page}"
yield scrapy.Request(url=url, callback=self.parse)
This spider starts at the first page of the quotes-API. With each
@@ -274,19 +280,22 @@ In more complex websites, it could be difficult to easily reproduce the
requests, as we could need to add ``headers`` or ``cookies`` to make it work.
In those cases you can export the requests in `cURL `_
format, by right-clicking on each of them in the network tool and using the
-:meth:`~scrapy.http.Request.from_curl()` method to generate an equivalent
-request::
+:meth:`~scrapy.Request.from_curl()` method to generate an equivalent
+request:
+
+.. code-block:: python
from scrapy import Request
request = Request.from_curl(
- "curl 'http://quotes.toscrape.com/api/quotes?page=1' -H 'User-Agent: Mozil"
+ "curl 'https://quotes.toscrape.com/api/quotes?page=1' -H 'User-Agent: Mozil"
"la/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0' -H 'Acce"
"pt: */*' -H 'Accept-Language: ca,en-US;q=0.7,en;q=0.3' --compressed -H 'X"
"-Requested-With: XMLHttpRequest' -H 'Proxy-Authorization: Basic QFRLLTAzM"
"zEwZTAxLTk5MWUtNDFiNC1iZWRmLTJjNGI4M2ZiNDBmNDpAVEstMDMzMTBlMDEtOTkxZS00MW"
"I0LWJlZGYtMmM0YjgzZmI0MGY0' -H 'Connection: keep-alive' -H 'Referer: http"
- "://quotes.toscrape.com/scroll' -H 'Cache-Control: max-age=0'")
+ "://quotes.toscrape.com/scroll' -H 'Cache-Control: max-age=0'"
+ )
Alternatively, if you want to know the arguments needed to recreate that
request you can use the :func:`~scrapy.utils.curl.curl_to_request_kwargs`
@@ -304,8 +313,8 @@ daunting and pages can be very complex, but it (mostly) boils down
to identifying the correct request and replicating it in your spider.
.. _Developer Tools: https://en.wikipedia.org/wiki/Web_development_tools
-.. _quotes.toscrape.com: http://quotes.toscrape.com
-.. _quotes.toscrape.com/scroll: http://quotes.toscrape.com/scroll
-.. _quotes.toscrape.com/api/quotes?page=10: http://quotes.toscrape.com/api/quotes?page=10
+.. _quotes.toscrape.com: https://quotes.toscrape.com
+.. _quotes.toscrape.com/scroll: https://quotes.toscrape.com/scroll
+.. _quotes.toscrape.com/api/quotes?page=10: https://quotes.toscrape.com/api/quotes?page=10
.. _has-class-extension: https://parsel.readthedocs.io/en/latest/usage.html#other-xpath-extensions
diff --git a/docs/topics/downloader-middleware.rst b/docs/topics/downloader-middleware.rst
index 06e614941..1abbc4968 100644
--- a/docs/topics/downloader-middleware.rst
+++ b/docs/topics/downloader-middleware.rst
@@ -17,10 +17,12 @@ To activate a downloader middleware component, add it to the
:setting:`DOWNLOADER_MIDDLEWARES` setting, which is a dict whose keys are the
middleware class paths and their values are the middleware orders.
-Here's an example::
+Here's an example:
+
+.. code-block:: python
DOWNLOADER_MIDDLEWARES = {
- 'myproject.middlewares.CustomDownloaderMiddleware': 543,
+ "myproject.middlewares.CustomDownloaderMiddleware": 543,
}
The :setting:`DOWNLOADER_MIDDLEWARES` setting is merged with the
@@ -42,11 +44,13 @@ previous (or subsequent) middleware being applied.
If you want to disable a built-in middleware (the ones defined in
:setting:`DOWNLOADER_MIDDLEWARES_BASE` and enabled by default) you must define it
in your project's :setting:`DOWNLOADER_MIDDLEWARES` setting and assign ``None``
-as its value. For example, if you want to disable the user-agent middleware::
+as its value. For example, if you want to disable the user-agent middleware:
+
+.. code-block:: python
DOWNLOADER_MIDDLEWARES = {
- 'myproject.middlewares.CustomDownloaderMiddleware': 543,
- 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
+ "myproject.middlewares.CustomDownloaderMiddleware": 543,
+ "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,
}
Finally, keep in mind that some middlewares may need to be enabled through a
@@ -76,7 +80,7 @@ object gives you access, for example, to the :ref:`settings `.
middleware.
:meth:`process_request` should either: return ``None``, return a
- :class:`~scrapy.http.Response` object, return a :class:`~scrapy.http.Request`
+ :class:`~scrapy.Response` object, return a :class:`~scrapy.http.Request`
object, or raise :exc:`~scrapy.exceptions.IgnoreRequest`.
If it returns ``None``, Scrapy will continue processing this request, executing all
@@ -88,8 +92,8 @@ object gives you access, for example, to the :ref:`settings `.
or the appropriate download function; it'll return that response. The :meth:`process_response`
methods of installed middleware is always called on every response.
- If it returns a :class:`~scrapy.http.Request` object, Scrapy will stop calling
- process_request methods and reschedule the returned request. Once the newly returned
+ If it returns a :class:`~scrapy.Request` object, Scrapy will stop calling
+ :meth:`process_request` methods and reschedule the returned request. Once the newly returned
request is performed, the appropriate middleware chain will be called on
the downloaded response.
@@ -100,22 +104,22 @@ object gives you access, for example, to the :ref:`settings `.
ignored and not logged (unlike other exceptions).
:param request: the request being processed
- :type request: :class:`~scrapy.http.Request` object
+ :type request: :class:`~scrapy.Request` object
:param spider: the spider for which this request is intended
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
.. method:: process_response(request, response, spider)
:meth:`process_response` should either: return a :class:`~scrapy.http.Response`
- object, return a :class:`~scrapy.http.Request` object or
+ object, return a :class:`~scrapy.Request` object or
raise a :exc:`~scrapy.exceptions.IgnoreRequest` exception.
If it returns a :class:`~scrapy.http.Response` (it could be the same given
response, or a brand-new one), that response will continue to be processed
with the :meth:`process_response` of the next middleware in the chain.
- If it returns a :class:`~scrapy.http.Request` object, the middleware chain is
+ If it returns a :class:`~scrapy.Request` object, the middleware chain is
halted and the returned request is rescheduled to be downloaded in the future.
This is the same behavior as if a request is returned from :meth:`process_request`.
@@ -124,13 +128,13 @@ object gives you access, for example, to the :ref:`settings `.
exception, it is ignored and not logged (unlike other exceptions).
:param request: the request that originated the response
- :type request: is a :class:`~scrapy.http.Request` object
+ :type request: is a :class:`~scrapy.Request` object
:param response: the response being processed
:type response: :class:`~scrapy.http.Response` object
:param spider: the spider for which this response is intended
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
.. method:: process_exception(request, exception, spider)
@@ -139,7 +143,7 @@ object gives you access, for example, to the :ref:`settings `.
exception (including an :exc:`~scrapy.exceptions.IgnoreRequest` exception)
:meth:`process_exception` should return: either ``None``,
- a :class:`~scrapy.http.Response` object, or a :class:`~scrapy.http.Request` object.
+ a :class:`~scrapy.http.Response` object, or a :class:`~scrapy.Request` object.
If it returns ``None``, Scrapy will continue processing this exception,
executing any other :meth:`process_exception` methods of installed middleware,
@@ -149,19 +153,19 @@ object gives you access, for example, to the :ref:`settings `.
method chain of installed middleware is started, and Scrapy won't bother calling
any other :meth:`process_exception` methods of middleware.
- If it returns a :class:`~scrapy.http.Request` object, the returned request is
+ If it returns a :class:`~scrapy.Request` object, the returned request is
rescheduled to be downloaded in the future. This stops the execution of
:meth:`process_exception` methods of the middleware the same as returning a
response would.
:param request: the request that generated the exception
- :type request: is a :class:`~scrapy.http.Request` object
+ :type request: is a :class:`~scrapy.Request` object
:param exception: the raised exception
:type exception: an ``Exception`` object
:param spider: the spider for which this request is intended
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
.. method:: from_crawler(cls, crawler)
@@ -203,10 +207,15 @@ CookiesMiddleware
browsers do.
.. caution:: When non-UTF8 encoded byte sequences are passed to a
- :class:`~scrapy.http.Request`, the ``CookiesMiddleware`` will log
+ :class:`~scrapy.Request`, the ``CookiesMiddleware`` will log
a warning. Refer to :ref:`topics-logging-advanced-customization`
to customize the logging behaviour.
+ .. caution:: Cookies set via the ``Cookie`` header are not considered by the
+ :ref:`cookies-mw`. If you need to set cookies for a request, use the
+ :class:`Request.cookies ` parameter. This is a known
+ current limitation that is being worked on.
+
The following settings can be used to configure the cookie middleware:
* :setting:`COOKIES_ENABLED`
@@ -221,20 +230,26 @@ There is support for keeping multiple cookie sessions per spider by using the
:reqmeta:`cookiejar` Request meta key. By default it uses a single cookie jar
(session), but you can pass an identifier to use different ones.
-For example::
+For example:
+
+.. skip: next
+.. code-block:: python
for i, url in enumerate(urls):
- yield scrapy.Request(url, meta={'cookiejar': i},
- callback=self.parse_page)
+ yield scrapy.Request(url, meta={"cookiejar": i}, callback=self.parse_page)
Keep in mind that the :reqmeta:`cookiejar` meta key is not "sticky". You need to keep
-passing it along on subsequent requests. For example::
+passing it along on subsequent requests. For example:
+
+.. code-block:: python
def parse_page(self, response):
# do some processing
- return scrapy.Request("http://www.example.com/otherpage",
- meta={'cookiejar': response.meta['cookiejar']},
- callback=self.parse_other_page)
+ return scrapy.Request(
+ "http://www.example.com/otherpage",
+ meta={"cookiejar": response.meta["cookiejar"]},
+ callback=self.parse_other_page,
+ )
.. setting:: COOKIES_ENABLED
@@ -253,7 +268,7 @@ web server and received cookies in :class:`~scrapy.http.Response` will
**not** be merged with the existing cookies.
For more detailed information see the ``cookies`` parameter in
-:class:`~scrapy.http.Request`.
+:class:`~scrapy.Request`.
.. setting:: COOKIES_DEBUG
@@ -318,18 +333,34 @@ HttpAuthMiddleware
This middleware authenticates all requests generated from certain spiders
using `Basic access authentication`_ (aka. HTTP auth).
- To enable HTTP authentication from certain spiders, set the ``http_user``
- and ``http_pass`` attributes of those spiders.
+ To enable HTTP authentication for a spider, set the ``http_user`` and
+ ``http_pass`` spider attributes to the authentication data and the
+ ``http_auth_domain`` spider attribute to the domain which requires this
+ authentication (its subdomains will be also handled in the same way).
+ You can set ``http_auth_domain`` to ``None`` to enable the
+ authentication for all requests but you risk leaking your authentication
+ credentials to unrelated domains.
- Example::
+ .. warning::
+ In previous Scrapy versions HttpAuthMiddleware sent the authentication
+ data with all requests, which is a security problem if the spider
+ makes requests to several different domains. Currently if the
+ ``http_auth_domain`` attribute is not set, the middleware will use the
+ domain of the first request, which will work for some spiders but not
+ for others. In the future the middleware will produce an error instead.
+
+ Example:
+
+ .. code-block:: python
from scrapy.spiders import CrawlSpider
- class SomeIntranetSiteSpider(CrawlSpider):
- http_user = 'someuser'
- http_pass = 'somepass'
- name = 'intranet.example.com'
+ class SomeIntranetSiteSpider(CrawlSpider):
+ http_user = "someuser"
+ http_pass = "somepass"
+ http_auth_domain = "intranet.example.com"
+ name = "intranet.example.com"
# .. rest of the spider code omitted ...
@@ -347,7 +378,7 @@ HttpCacheMiddleware
This middleware provides low-level cache to all HTTP requests and responses.
It has to be combined with a cache storage backend as well as a cache policy.
- Scrapy ships with three HTTP cache storage backends:
+ Scrapy ships with the following HTTP cache storage backends:
* :ref:`httpcache-storage-fs`
* :ref:`httpcache-storage-dbm`
@@ -496,7 +527,7 @@ defines the methods described below.
the :signal:`open_spider ` signal.
:param spider: the spider which has been opened
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
.. method:: close_spider(spider)
@@ -504,27 +535,27 @@ defines the methods described below.
the :signal:`close_spider ` signal.
:param spider: the spider which has been closed
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
.. method:: retrieve_response(spider, request)
Return response if present in cache, or ``None`` otherwise.
:param spider: the spider which generated the request
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
:param request: the request to find cached response for
- :type request: :class:`~scrapy.http.Request` object
+ :type request: :class:`~scrapy.Request` object
.. method:: store_response(spider, request, response)
Store the given response in the cache.
:param spider: the spider for which the response is intended
- :type spider: :class:`~scrapy.spiders.Spider` object
+ :type spider: :class:`~scrapy.Spider` object
:param request: the corresponding request the spider generated
- :type request: :class:`~scrapy.http.Request` object
+ :type request: :class:`~scrapy.Request` object
:param response: the response to store in the cache
:type response: :class:`~scrapy.http.Response` object
@@ -684,11 +715,15 @@ HttpCompressionMiddleware
This middleware allows compressed (gzip, deflate) traffic to be
sent/received from web sites.
- This middleware also supports decoding `brotli-compressed`_ responses,
- provided `brotlipy`_ is installed.
+ This middleware also supports decoding `brotli-compressed`_ as well as
+ `zstd-compressed`_ responses, provided that `brotli`_ or `zstandard`_ is
+ installed, respectively.
.. _brotli-compressed: https://www.ietf.org/rfc/rfc7932.txt
-.. _brotlipy: https://pypi.org/project/brotlipy/
+.. _brotli: https://pypi.org/project/Brotli/
+.. _zstd-compressed: https://www.ietf.org/rfc/rfc8478.txt
+.. _zstandard: https://pypi.org/project/zstandard/
+
HttpCompressionMiddleware Settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -714,7 +749,7 @@ HttpProxyMiddleware
.. class:: HttpProxyMiddleware
This middleware sets the HTTP proxy to use for requests, by setting the
- ``proxy`` meta value for :class:`~scrapy.http.Request` objects.
+ ``proxy`` meta value for :class:`~scrapy.Request` objects.
Like the Python standard library module :mod:`urllib.request`, it obeys
the following environment variables:
@@ -741,12 +776,12 @@ RedirectMiddleware
.. reqmeta:: redirect_urls
The urls which the request goes through (while being redirected) can be found
-in the ``redirect_urls`` :attr:`Request.meta ` key.
+in the ``redirect_urls`` :attr:`Request.meta ` key.
.. reqmeta:: redirect_reasons
The reason behind each redirect in :reqmeta:`redirect_urls` can be found in the
-``redirect_reasons`` :attr:`Request.meta