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 f347a0cd0..f76bf783d 100644
--- a/.bumpversion.cfg
+++ b/.bumpversion.cfg
@@ -1,5 +1,5 @@
[bumpversion]
-current_version = 2.0.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/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..dfbdf4208
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+tests/sample_data/** binary
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 ff6e2ea65..6c5c50e08 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,7 +14,15 @@ htmlcov/
.coverage
.pytest_cache/
.coverage.*
+coverage.*
+test-output.*
.cache/
+.mypy_cache/
+/tests/keys/localhost.crt
+/tests/keys/localhost.key
# 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 17eba34f3..e71d34f3a 100644
--- a/.readthedocs.yml
+++ b/.readthedocs.yml
@@ -1,11 +1,17 @@
version: 2
+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 66e1a9617..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,65 +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=pypy3
- - env: TOXENV=py35
- python: 3.5
- - env: TOXENV=pinned
- python: 3.5
- - env: TOXENV=py35-asyncio
- python: 3.5.2
- - env: TOXENV=py36
- python: 3.6
- - env: TOXENV=py37
- python: 3.7
- - env: TOXENV=py38
- python: 3.8
- - env: TOXENV=extra-deps
- python: 3.8
- - env: TOXENV=py38-asyncio
- python: 3.8
- - env: TOXENV=docs
- python: 3.7 # Keep in sync with .readthedocs.yml
-install:
- - |
- if [ "$TOXENV" = "pypy3" ]; then
- export PYPY_VERSION="pypy3.5-5.9-beta-linux_x86_64-portable"
- wget "https://bitbucket.org/squeaky/portable-pypy/downloads/${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: "$TOXENV == py37 && $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 ce5973bcd..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.5+
+* 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/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 7fd636864..000000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-platform: x86
-version: '{branch}-{build}'
-environment:
- matrix:
- - PYTHON: "C:\\Python36"
- TOX_ENV: py36
-
-branches:
- only:
- - master
- - /d+\.\d+\.\d+[\w\-]*$/
-
-install:
- - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
- - "SET PYTHONPATH=%APPVEYOR_BUILD_FOLDER%"
- - "SET TOX_TESTENV_PASSENV=HOME HOMEDRIVE HOMEPATH PYTHONPATH USERPROFILE"
- - "pip install -U tox"
-
-build: false
-skip_tags: true
-test_script:
- - "tox -e %TOX_ENV%"
-
-cache:
- - '%LOCALAPPDATA%\pip\cache'
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/conftest.py b/conftest.py
index be5fbabf4..2bfa46f5a 100644
--- a/conftest.py
+++ b/conftest.py
@@ -1,25 +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"),
- # Py36-only parts of respective tests
- *_py_files("tests/py36"),
+ # 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()
@@ -28,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
@@ -49,5 +68,37 @@ 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
+generate_keys()
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 0a343cd19..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
@@ -57,3 +57,12 @@ There is a way to recreate the doc automatically when you make changes, you
need to install watchdog (``pip install watchdog``) and then use::
make watch
+
+Alternative method using tox
+----------------------------
+
+To compile the documentation to HTML run the following command::
+
+ tox -e docs
+
+Documentation will be generated (in HTML format) inside the ``.tox/docs/tmp/html`` dir.
diff --git a/docs/_ext/scrapydocs.py b/docs/_ext/scrapydocs.py
index 192123473..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:
- # [(u'pair', u'SETTING_NAME; setting', u'std:setting-SETTING_NAME', '')]
- entry_type, info, refid = node['entries'][0][:3]
- return entry_type == 'pair' and info.endswith('; setting')
+ # [('pair', 'SETTING_NAME; setting', 'std:setting-SETTING_NAME', '')]
+ 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 6e2399f66..9ca0f817a 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-#
# Scrapy documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 24 12:02:52 2008.
#
@@ -13,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
@@ -28,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 = '2008–{}, Scrapy developers'.format(datetime.now().year)
+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
@@ -60,47 +57,51 @@ copyright = '2008–{}, Scrapy developers'.format(datetime.now().year)
# 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"]
# Options for HTML output
@@ -108,19 +109,19 @@ pygments_style = 'sphinx'
# 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
@@ -129,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
@@ -174,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
@@ -223,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/",
]
@@ -234,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",
]
@@ -280,18 +275,47 @@ coverage_ignore_pyobjects = [
# -------------------------------------
intersphinx_mapping = {
- 'coverage': ('https://coverage.readthedocs.io/en/stable', None),
- 'cssselect': ('https://cssselect.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
# ------------------------------------
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"]
+
+
+def setup(app):
+ 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 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 aed5ab92e..d728338da 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:
@@ -108,6 +114,11 @@ Well-written patches should:
tox -e docs-coverage
+* if you are removing deprecated code, first make sure that at least 1 year
+ (12 months) has passed since the release that introduced the deprecation.
+ See :ref:`deprecation-policy`.
+
+
.. _submitting-patches:
Submitting patches
@@ -135,7 +146,7 @@ original pull request author hasn't had time to address them.
In this case consider picking up this pull request: open
a new pull request with all commits from the original pull request, as well as
additional changes to address the raised issues. Doing so helps a lot; it is
-not considered rude as soon as the original author is acknowledged by keeping
+not considered rude as long as the original author is acknowledged by keeping
his/her commits.
You can pull an existing pull request to a local branch
@@ -155,22 +166,52 @@ Finally, try to keep aesthetic changes (:pep:`8` compliance, unused imports
removal, etc) in separate commits from functional changes. This will make pull
requests easier to review and more likely to get merged.
+
+.. _coding-style:
+
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 80 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 pre-commit``.
* 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
@@ -191,11 +232,22 @@ In any case, if something is covered in a docstring, use the
documentation instead of duplicating the docstring in files within the
``docs/`` directory.
+Documentation updates that cover new or modified features must use Sphinx’s
+:rst:dir:`versionadded` and :rst:dir:`versionchanged` directives. Use
+``VERSION`` as version, we will replace it with the actual version right before
+the corresponding release. When we release a new major or minor version of
+Scrapy, we remove these directives if they are older than 3 years.
+
+Documentation about deprecated features must be removed as those features are
+deprecated, so that new readers do not run into it. New deprecations and
+deprecation removals are documented in the :ref:`release notes `.
+
+
Tests
=====
Tests are implemented using the :doc:`Twisted unit-testing framework
-`. Running tests requires
+`. Running tests requires
:doc:`tox `.
.. _running-tests:
@@ -213,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
@@ -231,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:
@@ -268,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 75a0f4864..2113b0964 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::
@@ -64,20 +61,6 @@ Here's an example spider using BeautifulSoup API, with ``lxml`` as the HTML pars
.. _BeautifulSoup's official documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use
-.. _faq-python-versions:
-
-What Python versions does Scrapy support?
------------------------------------------
-
-Scrapy is supported under Python 3.5+
-under CPython (default Python implementation) and PyPy (starting with PyPy 5.9).
-Python 3 support was added in Scrapy 1.1.
-PyPy support was added in Scrapy 1.4, PyPy3 support was added in Scrapy 1.5.
-Python 2 support was dropped in Scrapy 2.0.
-
-.. note::
- For Python 3 support on Windows, it is recommended to use
- Anaconda/Miniconda as :ref:`outlined in the installation guide `.
Did Scrapy "steal" X from Django?
---------------------------------
@@ -108,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?
---------------------------------------------
@@ -132,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
@@ -159,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?
--------------------------------------------------
@@ -218,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
@@ -250,15 +267,15 @@ Simplest way to dump all my scraped items into a JSON/CSV/XML file?
To dump into a JSON file::
- scrapy crawl myspider -o items.json
+ scrapy crawl myspider -O items.json
To dump into a CSV file::
- scrapy crawl myspider -o items.csv
+ scrapy crawl myspider -O items.csv
To dump into a XML file::
- scrapy crawl myspider -o items.xml
+ scrapy crawl myspider -O items.xml
For more information see :ref:`topics-feed-exports`
@@ -329,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?
@@ -338,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 scrapy.item import BaseItem
+ from itemadapter import is_item, ItemAdapter
class MultiplyItemsMiddleware:
-
def process_spider_output(self, response, result, spider):
for item in result:
- if isinstance(item, (BaseItem, dict)):
- for _ in range(item['multiply_by']):
+ if is_item(item):
+ adapter = ItemAdapter(item)
+ for _ in range(adapter["multiply_by"]):
yield deepcopy(item)
Does Scrapy support IPv6 addresses?
@@ -371,7 +391,49 @@ Twisted reactor is :class:`twisted.internet.selectreactor.SelectReactor`. Switch
different reactor is possible by using the :setting:`TWISTED_REACTOR` setting.
+.. _faq-stop-response-download:
+
+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, 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.
+
+
+.. _faq-blank-request:
+
+How can I make a blank request?
+-------------------------------
+
+.. code-block:: python
+
+ from scrapy import Request
+
+
+ blank_request = Request("data:,")
+
+In this case, the URL is set to a data URI scheme. Data URLs allow you to include data
+in-line in web pages as if they were external resources. The "data:" scheme with an empty
+content (",") essentially creates a request to a data URL without any specific content.
+
+
+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 11aa5c9be..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
@@ -78,7 +82,6 @@ Basic concepts
topics/settings
topics/exceptions
-
:doc:`topics/commands`
Learn about the command-line tool used to manage your Scrapy project.
@@ -127,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.
@@ -141,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
=========================
@@ -223,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.
@@ -243,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 6356e0eea..c90c1d2bf 100644
--- a/docs/intro/install.rst
+++ b/docs/intro/install.rst
@@ -4,12 +4,19 @@
Installation guide
==================
+.. _faq-python-versions:
+
+Supported Python versions
+=========================
+
+Scrapy requires Python 3.8+, either the CPython implementation (default) or
+the PyPy implementation (see :ref:`python:implementations`).
+
+.. _intro-install-scrapy:
+
Installing Scrapy
=================
-Scrapy runs on Python 3.5 or above under CPython (default Python
-implementation) and PyPy (starting with PyPy 5.9).
-
If you're using `Anaconda`_ or `Miniconda`_, you can install the package from
the `conda-forge`_ channel, which has up-to-date packages for Linux, Windows
and macOS.
@@ -23,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.
@@ -45,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 `.
@@ -63,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:
@@ -112,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:
@@ -163,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
@@ -202,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 dependencides now have binary wheels for CPython, but not for PyPy.
-This means that these dependecies will be built during installation.
-On macOS, you are likely to face an issue with building Cryptography dependency,
-solution to this problem is described
+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 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
@@ -259,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 01986b594..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,52 +20,42 @@ 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()
if next_page is not None:
yield response.follow(next_page, self.parse)
-
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.json
+ scrapy runspider quotes_spider.py -o quotes.jsonl
+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::
-When this finishes you will have in the ``quotes.json`` file a list of the
-quotes in JSON format, containing text and author, looking like this (reformatted
-here for better readability)::
-
- [{
- "author": "Jane Austen",
- "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"
- },
- {
- "author": "Groucho Marx",
- "text": "\u201cOutside of a dog, a book is man's best friend. Inside of a dog it's too dark to read.\u201d"
- },
- {
- "author": "Steve Martin",
- "text": "\u201cA day without sunshine is like, you know, night.\u201d"
- },
- ...]
+ {"author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"}
+ {"author": "Steve Martin", "text": "\u201cA day without sunshine is like, you know, night.\u201d"}
+ {"author": "Garrison Keillor", "text": "\u201cAnyone who thinks sitting in church can make you a Christian must also think that sitting in a garage can make you a car.\u201d"}
+ ...
What just happened?
diff --git a/docs/intro/tutorial.rst b/docs/intro/tutorial.rst
index 1768badbb..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:
@@ -25,16 +25,16 @@ Scrapy.
If you're already familiar with other languages, and want to learn Python quickly, the `Python Tutorial`_ is a good resource.
If you're new to programming and want to start with Python, the following books
-may be useful to you:
+may be useful to you:
* `Automate the Boring Stuff With Python`_
-* `How To Think Like a Computer Scientist`_
+* `How To Think Like a Computer Scientist`_
-* `Learn Python 3 The Hard Way`_
+* `Learn Python 3 The Hard Way`_
You can also take a look at `this list of Python resources for non-programmers`_,
-as well as the `suggested resources in the learnpython-subreddit`_.
+as well as the `suggested resources in the learnpython-subreddit`_.
.. _Python: https://www.python.org/
.. _this list of Python resources for non-programmers: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
@@ -62,7 +62,7 @@ This will create a ``tutorial`` directory with the following contents::
__init__.py
items.py # project items definition file
-
+
middlewares.py # project middlewares file
pipelines.py # project pipelines file
@@ -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 = 'quotes-%s.html' % page
- with open(filename, 'wb') as f:
- f.write(response.body)
- self.log('Saved file %s' % 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 = 'quotes-%s.html' % page
- 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
@@ -287,17 +317,19 @@ to be scraped, you can at least get **some** data.
Besides the :meth:`~scrapy.selector.SelectorList.getall` and
:meth:`~scrapy.selector.SelectorList.get` methods, you can also use
-the :meth:`~scrapy.selector.SelectorList.re` method to extract using `regular
-expressions`_:
+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`).
@@ -305,7 +337,6 @@ with a selector (see :ref:`topics-developer-tools`).
`Selector Gadget`_ is also a nice tool to quickly find CSS selector for
visually selected elements, which works in many browsers.
-.. _regular expressions: https://docs.python.org/3/library/re.html
.. _Selector Gadget: https://selectorgadget.com/
@@ -314,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
@@ -346,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
@@ -370,55 +403,64 @@ 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
from sys import version_info
-.. skip: next if(version_info < (3, 6), reason="Only Python 3.6+ dictionaries match the output")
-
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
-----------------------------
@@ -429,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
@@ -437,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.”"}
@@ -465,24 +517,23 @@ Storing the scraped data
The simplest way to store the scraped data is by using :ref:`Feed exports
`, with the following command::
- scrapy crawl quotes -o quotes.json
+ 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`_.
-For historic reasons, Scrapy appends to a given file instead of overwriting
-its contents. If you run this command twice without removing the file
-before the second time, you'll end up with a broken JSON file.
+The ``-O`` command-line switch overwrites any existing file; use ``-o`` instead
+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`_::
-You can also use other formats, like `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
@@ -499,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.
@@ -525,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
@@ -543,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)
@@ -586,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
@@ -594,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)
@@ -613,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
@@ -674,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.
@@ -705,14 +778,16 @@ Using spider arguments
You can provide command line arguments to your spiders by using the ``-a``
option when running them::
- scrapy crawl quotes -o quotes-humor.json -a tag=humor
+ scrapy crawl quotes -O quotes-humor.json -a tag=humor
These arguments are passed to the Spider's ``__init__`` method and become
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
@@ -721,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 e9b7140cd..d90e32560 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -3,6 +3,2418 @@
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`)
+
+- The :func:`scrapy.utils.response.response_httprepr` function, deprecated in
+ Scrapy 2.6.0, has now been removed. (:issue:`6111`)
+
+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.
+
+- :func:`scrapy.utils.response.response_httprepr` is now deprecated.
+ (:issue:`4972`)
+
+
+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)
+-------------------------
+
+Highlights:
+
+* :ref:`Feed exports ` now support :ref:`Google Cloud
+ Storage ` as a storage backend
+
+* The new :setting:`FEED_EXPORT_BATCH_ITEM_COUNT` setting allows to deliver
+ output items in batches of up to the specified number of items.
+
+ It also serves as a workaround for :ref:`delayed file delivery
+ `, which causes Scrapy to only start item delivery
+ after the crawl has finished when using certain storage backends
+ (:ref:`S3 `, :ref:`FTP `,
+ and now :ref:`GCS `).
+
+* The base implementation of :ref:`item loaders ` has been
+ moved into a separate library, :doc:`itemloaders `,
+ allowing usage from outside Scrapy and a separate release schedule
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+* Removed the following classes and their parent modules from
+ ``scrapy.linkextractors``:
+
+ * ``htmlparser.HtmlParserLinkExtractor``
+ * ``regex.RegexLinkExtractor``
+ * ``sgml.BaseSgmlLinkExtractor``
+ * ``sgml.SgmlLinkExtractor``
+
+ Use
+ :class:`LinkExtractor `
+ instead (:issue:`4356`, :issue:`4679`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+* The ``scrapy.utils.python.retry_on_eintr`` function is now deprecated
+ (:issue:`4683`)
+
+
+New features
+~~~~~~~~~~~~
+
+* :ref:`Feed exports ` support :ref:`Google Cloud
+ Storage ` (:issue:`685`, :issue:`3608`)
+
+* New :setting:`FEED_EXPORT_BATCH_ITEM_COUNT` setting for batch deliveries
+ (:issue:`4250`, :issue:`4434`)
+
+* The :command:`parse` command now allows specifying an output file
+ (:issue:`4317`, :issue:`4377`)
+
+* :meth:`Request.from_curl ` and
+ :func:`~scrapy.utils.curl.curl_to_request_kwargs` now also support
+ ``--data-raw`` (:issue:`4612`)
+
+* A ``parse`` callback may now be used in built-in spider subclasses, such
+ as :class:`~scrapy.spiders.CrawlSpider` (:issue:`712`, :issue:`732`,
+ :issue:`781`, :issue:`4254` )
+
+
+Bug fixes
+~~~~~~~~~
+
+* Fixed the :ref:`CSV exporting ` of
+ :ref:`dataclass items ` and :ref:`attr.s items
+ ` (:issue:`4667`, :issue:`4668`)
+
+* :meth:`Request.from_curl ` and
+ :func:`~scrapy.utils.curl.curl_to_request_kwargs` now set the request
+ method to ``POST`` when a request body is specified and no request method
+ is specified (:issue:`4612`)
+
+* The processing of ANSI escape sequences in enabled in Windows 10.0.14393
+ and later, where it is required for colored output (:issue:`4393`,
+ :issue:`4403`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+* Updated the `OpenSSL cipher list format`_ link in the documentation about
+ the :setting:`DOWNLOADER_CLIENT_TLS_CIPHERS` setting (:issue:`4653`)
+
+* Simplified the code example in :ref:`topics-loaders-dataclass`
+ (:issue:`4652`)
+
+.. _OpenSSL cipher list format: https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+* The base implementation of :ref:`item loaders ` has been
+ moved into :doc:`itemloaders ` (:issue:`4005`,
+ :issue:`4516`)
+
+* Fixed a silenced error in some scheduler tests (:issue:`4644`,
+ :issue:`4645`)
+
+* Renewed the localhost certificate used for SSL tests (:issue:`4650`)
+
+* Removed cookie-handling code specific to Python 2 (:issue:`4682`)
+
+* Stopped using Python 2 unicode literal syntax (:issue:`4704`)
+
+* Stopped using a backlash for line continuation (:issue:`4673`)
+
+* Removed unneeded entries from the MyPy exception list (:issue:`4690`)
+
+* Automated tests now pass on Windows as part of our continuous integration
+ system (:issue:`4458`)
+
+* Automated tests now pass on the latest PyPy version for supported Python
+ versions in our continuous integration system (:issue:`4504`)
+
+
+.. _release-2.2.1:
+
+Scrapy 2.2.1 (2020-07-17)
+-------------------------
+
+* The :command:`startproject` command no longer makes unintended changes to
+ the permissions of files in the destination folder, such as removing
+ execution permissions (:issue:`4662`, :issue:`4666`)
+
+
+.. _release-2.2.0:
+
+Scrapy 2.2.0 (2020-06-24)
+-------------------------
+
+Highlights:
+
+* Python 3.5.2+ is required now
+* :ref:`dataclass objects ` and
+ :ref:`attrs objects ` are now valid :ref:`item types
+ `
+* New :meth:`TextResponse.json ` method
+* New :signal:`bytes_received` signal that allows canceling response download
+* :class:`~scrapy.downloadermiddlewares.cookies.CookiesMiddleware` fixes
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+* Support for Python 3.5.0 and 3.5.1 has been dropped; Scrapy now refuses to
+ run with a Python version lower than 3.5.2, which introduced
+ :class:`typing.Type` (:issue:`4615`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+* :meth:`TextResponse.body_as_unicode
+ ` is now deprecated, use
+ :attr:`TextResponse.text ` instead
+ (:issue:`4546`, :issue:`4555`, :issue:`4579`)
+
+* :class:`scrapy.item.BaseItem` is now deprecated, use
+ :class:`scrapy.item.Item` instead (:issue:`4534`)
+
+
+New features
+~~~~~~~~~~~~
+
+* :ref:`dataclass objects ` and
+ :ref:`attrs objects ` are now valid :ref:`item types
+ `, and a new itemadapter_ library makes it easy to
+ write code that :ref:`supports any item type `
+ (:issue:`2749`, :issue:`2807`, :issue:`3761`, :issue:`3881`, :issue:`4642`)
+
+* A new :meth:`TextResponse.json ` method
+ allows to deserialize JSON responses (:issue:`2444`, :issue:`4460`,
+ :issue:`4574`)
+
+* A new :signal:`bytes_received` signal allows monitoring response download
+ progress and :ref:`stopping downloads `
+ (:issue:`4205`, :issue:`4559`)
+
+* The dictionaries in the result list of a :ref:`media pipeline
+ ` now include a new key, ``status``, which indicates
+ if the file was downloaded or, if the file was not downloaded, why it was
+ not downloaded; see :meth:`FilesPipeline.get_media_requests
+ ` for more
+ information (:issue:`2893`, :issue:`4486`)
+
+* When using :ref:`Google Cloud Storage ` for
+ a :ref:`media pipeline `, a warning is now logged if
+ the configured credentials do not grant the required permissions
+ (:issue:`4346`, :issue:`4508`)
+
+* :ref:`Link extractors ` are now serializable,
+ as long as you do not use :ref:`lambdas ` for parameters; for
+ example, you can now pass link extractors in :attr:`Request.cb_kwargs
+ ` or
+ :attr:`Request.meta ` when :ref:`persisting
+ scheduled requests ` (:issue:`4554`)
+
+* Upgraded the :ref:`pickle protocol ` that Scrapy uses
+ from protocol 2 to protocol 4, improving serialization capabilities and
+ performance (:issue:`4135`, :issue:`4541`)
+
+* :func:`scrapy.utils.misc.create_instance` now raises a :exc:`TypeError`
+ exception if the resulting instance is ``None`` (:issue:`4528`,
+ :issue:`4532`)
+
+.. _itemadapter: https://github.com/scrapy/itemadapter
+
+
+Bug fixes
+~~~~~~~~~
+
+* :class:`~scrapy.downloadermiddlewares.cookies.CookiesMiddleware` no longer
+ discards cookies defined in :attr:`Request.headers
+ ` (:issue:`1992`, :issue:`2400`)
+
+* :class:`~scrapy.downloadermiddlewares.cookies.CookiesMiddleware` no longer
+ re-encodes cookies defined as :class:`bytes` in the ``cookies`` parameter
+ of the ``__init__`` method of :class:`~scrapy.http.Request`
+ (:issue:`2400`, :issue:`3575`)
+
+* When :setting:`FEEDS` defines multiple URIs, :setting:`FEED_STORE_EMPTY` is
+ ``False`` and the crawl yields no items, Scrapy no longer stops feed
+ exports after the first URI (:issue:`4621`, :issue:`4626`)
+
+* :class:`~scrapy.spiders.Spider` callbacks defined using :doc:`coroutine
+ syntax ` no longer need to return an iterable, and may
+ instead return a :class:`~scrapy.http.Request` object, an
+ :ref:`item `, or ``None`` (:issue:`4609`)
+
+* The :command:`startproject` command now ensures that the generated project
+ folders and files have the right permissions (:issue:`4604`)
+
+* Fix a :exc:`KeyError` exception being sometimes raised from
+ :class:`scrapy.utils.datatypes.LocalWeakReferencedCache` (:issue:`4597`,
+ :issue:`4599`)
+
+* When :setting:`FEEDS` defines multiple URIs, log messages about items being
+ stored now contain information from the corresponding feed, instead of
+ always containing information about only one of the feeds (:issue:`4619`,
+ :issue:`4629`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+* Added a new section about :ref:`accessing cb_kwargs from errbacks
+ ` (:issue:`4598`, :issue:`4634`)
+
+* Covered chompjs_ in :ref:`topics-parsing-javascript` (:issue:`4556`,
+ :issue:`4562`)
+
+* Removed from :doc:`topics/coroutines` the warning about the API being
+ experimental (:issue:`4511`, :issue:`4513`)
+
+* Removed references to unsupported versions of :doc:`Twisted
+ ` (:issue:`4533`)
+
+* Updated the description of the :ref:`screenshot pipeline example
+ `, which now uses :doc:`coroutine syntax
+ ` instead of returning a
+ :class:`~twisted.internet.defer.Deferred` (:issue:`4514`, :issue:`4593`)
+
+* Removed a misleading import line from the
+ :func:`scrapy.utils.log.configure_logging` code example (:issue:`4510`,
+ :issue:`4587`)
+
+* The display-on-hover behavior of internal documentation references now also
+ covers links to :ref:`commands `, :attr:`Request.meta
+ ` keys, :ref:`settings ` and
+ :ref:`signals ` (:issue:`4495`, :issue:`4563`)
+
+* It is again possible to download the documentation for offline reading
+ (:issue:`4578`, :issue:`4585`)
+
+* Removed backslashes preceding ``*args`` and ``**kwargs`` in some function
+ and method signatures (:issue:`4592`, :issue:`4596`)
+
+.. _chompjs: https://github.com/Nykakin/chompjs
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+* Adjusted the code base further to our :ref:`style guidelines
+ ` (:issue:`4237`, :issue:`4525`, :issue:`4538`,
+ :issue:`4539`, :issue:`4540`, :issue:`4542`, :issue:`4543`, :issue:`4544`,
+ :issue:`4545`, :issue:`4557`, :issue:`4558`, :issue:`4566`, :issue:`4568`,
+ :issue:`4572`)
+
+* Removed remnants of Python 2 support (:issue:`4550`, :issue:`4553`,
+ :issue:`4568`)
+
+* Improved code sharing between the :command:`crawl` and :command:`runspider`
+ commands (:issue:`4548`, :issue:`4552`)
+
+* Replaced ``chain(*iterable)`` with ``chain.from_iterable(iterable)``
+ (:issue:`4635`)
+
+* You may now run the :mod:`asyncio` tests with Tox on any Python version
+ (:issue:`4521`)
+
+* Updated test requirements to reflect an incompatibility with pytest 5.4 and
+ 5.4.1 (:issue:`4588`)
+
+* Improved :class:`~scrapy.spiderloader.SpiderLoader` test coverage for
+ scenarios involving duplicate spider names (:issue:`4549`, :issue:`4560`)
+
+* Configured Travis CI to also run the tests with Python 3.5.2
+ (:issue:`4518`, :issue:`4615`)
+
+* Added a `Pylint `_ job to Travis CI
+ (:issue:`3727`)
+
+* Added a `Mypy `_ job to Travis CI (:issue:`4637`)
+
+* Made use of set literals in tests (:issue:`4573`)
+
+* Cleaned up the Travis CI configuration (:issue:`4517`, :issue:`4519`,
+ :issue:`4522`, :issue:`4537`)
+
+
+.. _release-2.1.0:
+
+Scrapy 2.1.0 (2020-04-24)
+-------------------------
+
+Highlights:
+
+* New :setting:`FEEDS` setting to export to multiple feeds
+* New :attr:`Response.ip_address ` attribute
+
+Backward-incompatible changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+* :exc:`AssertionError` exceptions triggered by :ref:`assert `
+ statements have been replaced by new exception types, to support running
+ Python in optimized mode (see :option:`-O`) without changing Scrapy’s
+ behavior in any unexpected ways.
+
+ If you catch an :exc:`AssertionError` exception from Scrapy, update your
+ code to catch the corresponding new exception.
+
+ (:issue:`4440`)
+
+
+Deprecation removals
+~~~~~~~~~~~~~~~~~~~~
+
+* The ``LOG_UNSERIALIZABLE_REQUESTS`` setting is no longer supported, use
+ :setting:`SCHEDULER_DEBUG` instead (:issue:`4385`)
+
+* The ``REDIRECT_MAX_METAREFRESH_DELAY`` setting is no longer supported, use
+ :setting:`METAREFRESH_MAXDELAY` instead (:issue:`4385`)
+
+* The :class:`~scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware`
+ middleware has been removed, including the entire
+ :class:`scrapy.downloadermiddlewares.chunked` module; chunked transfers
+ work out of the box (:issue:`4431`)
+
+* The ``spiders`` property has been removed from
+ :class:`~scrapy.crawler.Crawler`, use :class:`CrawlerRunner.spider_loader
+ ` or instantiate
+ :setting:`SPIDER_LOADER_CLASS` with your settings instead (:issue:`4398`)
+
+* The ``MultiValueDict``, ``MultiValueDictKeyError``, and ``SiteNode``
+ classes have been removed from :mod:`scrapy.utils.datatypes`
+ (:issue:`4400`)
+
+
+Deprecations
+~~~~~~~~~~~~
+
+* The ``FEED_FORMAT`` and ``FEED_URI`` settings have been deprecated in
+ favor of the new :setting:`FEEDS` setting (:issue:`1336`, :issue:`3858`,
+ :issue:`4507`)
+
+
+New features
+~~~~~~~~~~~~
+
+* A new setting, :setting:`FEEDS`, allows configuring multiple output feeds
+ with different settings each (:issue:`1336`, :issue:`3858`, :issue:`4507`)
+
+* The :command:`crawl` and :command:`runspider` commands now support multiple
+ ``-o`` parameters (:issue:`1336`, :issue:`3858`, :issue:`4507`)
+
+* The :command:`crawl` and :command:`runspider` commands now support
+ specifying an output format by appending ``:`` to the output file
+ (:issue:`1336`, :issue:`3858`, :issue:`4507`)
+
+* The new :attr:`Response.ip_address `
+ attribute gives access to the IP address that originated a response
+ (:issue:`3903`, :issue:`3940`)
+
+* A warning is now issued when a value in
+ :attr:`~scrapy.spiders.Spider.allowed_domains` includes a port
+ (:issue:`50`, :issue:`3198`, :issue:`4413`)
+
+* Zsh completion now excludes used option aliases from the completion list
+ (:issue:`4438`)
+
+
+Bug fixes
+~~~~~~~~~
+
+* :ref:`Request serialization ` no longer breaks for
+ callbacks that are spider attributes which are assigned a function with a
+ different name (:issue:`4500`)
+
+* ``None`` values in :attr:`~scrapy.spiders.Spider.allowed_domains` no longer
+ cause a :exc:`TypeError` exception (:issue:`4410`)
+
+* Zsh completion no longer allows options after arguments (:issue:`4438`)
+
+* zope.interface 5.0.0 and later versions are now supported
+ (:issue:`4447`, :issue:`4448`)
+
+* ``Spider.make_requests_from_url``, deprecated in Scrapy 1.4.0, now issues a
+ warning when used (:issue:`4412`)
+
+
+Documentation
+~~~~~~~~~~~~~
+
+* Improved the documentation about signals that allow their handlers to
+ return a :class:`~twisted.internet.defer.Deferred` (:issue:`4295`,
+ :issue:`4390`)
+
+* Our PyPI entry now includes links for our documentation, our source code
+ repository and our issue tracker (:issue:`4456`)
+
+* Covered the `curl2scrapy `_
+ service in the documentation (:issue:`4206`, :issue:`4455`)
+
+* Removed references to the Guppy library, which only works in Python 2
+ (:issue:`4285`, :issue:`4343`)
+
+* Extended use of InterSphinx to link to Python 3 documentation
+ (:issue:`4444`, :issue:`4445`)
+
+* Added support for Sphinx 3.0 and later (:issue:`4475`, :issue:`4480`,
+ :issue:`4496`, :issue:`4503`)
+
+
+Quality assurance
+~~~~~~~~~~~~~~~~~
+
+* Removed warnings about using old, removed settings (:issue:`4404`)
+
+* Removed a warning about importing
+ :class:`~twisted.internet.testing.StringTransport` from
+ ``twisted.test.proto_helpers`` in Twisted 19.7.0 or newer (:issue:`4409`)
+
+* Removed outdated Debian package build files (:issue:`4384`)
+
+* Removed :class:`object` usage as a base class (:issue:`4430`)
+
+* Removed code that added support for old versions of Twisted that we no
+ longer support (:issue:`4472`)
+
+* Fixed code style issues (:issue:`4468`, :issue:`4469`, :issue:`4471`,
+ :issue:`4481`)
+
+* Removed :func:`twisted.internet.defer.returnValue` calls (:issue:`4443`,
+ :issue:`4446`, :issue:`4489`)
+
+
.. _release-2.0.1:
Scrapy 2.0.1 (2020-03-18)
@@ -212,7 +2624,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`)
@@ -466,6 +2878,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)
@@ -509,11 +3056,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')``).
@@ -631,6 +3180,8 @@ Deprecation removals
* ``scrapy.xlib`` has been removed (:issue:`4015`)
+.. _1.8-deprecations:
+
Deprecations
~~~~~~~~~~~~
@@ -764,7 +3315,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
@@ -987,6 +3538,8 @@ The following deprecated settings have also been removed (:issue:`3578`):
* ``SPIDER_MANAGER_CLASS`` (use :setting:`SPIDER_LOADER_CLASS`)
+.. _1.7-deprecations:
+
Deprecations
~~~~~~~~~~~~
@@ -1468,7 +4021,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`)
@@ -1505,7 +4058,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
@@ -1626,7 +4179,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
~~~~~~~~~~~~~
@@ -1800,7 +4353,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
~~~~~~~~~~~
@@ -2087,8 +4640,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
~~~~~~~~
@@ -2663,7 +5214,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`)
@@ -2788,7 +5339,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`)
@@ -2813,7 +5364,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`)
@@ -2993,7 +5544,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`)
@@ -3027,8 +5578,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)
@@ -3170,7 +5721,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