Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Merge branch 'master' into response_ip_address

Eugenio Lacuestaa44942d27d38
diff --cc conftest.py
index 55294feca,be5fbabf4..b39d644a5
--- a/conftest.py
+++ b/conftest.py
@@@ -12,7 -12,8 +12,10 @@@ collect_ignore =
"scrapy/utils/testsite.py",
# contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess
*_py_files("tests/CrawlerProcess"),
++ # contains scripts to be run by tests/test_crawler.py::CrawlerRunnerSubprocess
+ *_py_files("tests/CrawlerRunner"),
+ # Py36-only parts of respective tests
+ *_py_files("tests/py36"),
]
for line in open('tests/ignores.txt'):
diff --cc docs/topics/request-response.rst
index 8f2504a33,f009facd6..b5f5aff83
--- a/docs/topics/request-response.rst
+++ b/docs/topics/request-response.rst
@@@ -609,11 -609,11 +609,14 @@@ Response object
:param request: the initial value of the :attr:`Response.request` attribute.
This represents the :class:`Request` that generated this response.
- :type request: :class:`Request` object
+ :type request: scrapy.http.Request
+
+ :param certificate: an object representing the server's SSL certificate.
+ :type certificate: twisted.internet.ssl.Certificate
+ :param ip_address: The IP address of the server from which the Response originated.
+ :type ip_address: :class:`ipaddress.IPv4Address` or :class:`ipaddress.IPv6Address`
+
.. attribute:: Response.url
A string containing the URL of the response.
@@@ -682,14 -694,13 +697,21 @@@
they're shown on the string representation of the Response (`__str__`
method) which is used by the engine for logging.
+ .. attribute:: Response.certificate
+
+ A :class:`twisted.internet.ssl.Certificate` object representing
+ the server's SSL certificate.
+
+ Only populated for ``https`` responses, ``None`` otherwise.
+
+ .. attribute:: Response.ip_address
+
+ The IP address of the server from which the Response originated.
+
+ This attribute is currently only populated by the HTTP 1.1 download
+ handler, i.e. for ``http(s)`` responses. For other handlers,
+ :attr:`ip_address` is always ``None``.
+
.. method:: Response.copy()
Returns a new Response which is a copy of this Response.
diff --cc scrapy/core/downloader/handlers/http11.py
index b690f439f,93951d3b5..e72275021
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@@ -3,8 -3,8 +3,9 @@@
import logging
import re
import warnings
+ from contextlib import suppress
from io import BytesIO
+from ipaddress import ip_address
from time import time
from urllib.parse import urldefrag
@@@ -419,11 -419,12 +420,12 @@@ class ScrapyAgent(object)
return d
def _cb_bodydone(self, result, request, url):
- txresponse, body, flags, ip_address = result
- txresponse, body, flags, certificate = result
++ txresponse, body, flags, certificate, ip_address = result
status = int(txresponse.code)
headers = Headers(txresponse.headers.getAllRawHeaders())
respcls = responsetypes.from_args(headers=headers, url=url, body=body)
- return respcls(url=url, status=status, headers=headers, body=body, flags=flags, ip_address=ip_address)
+ return respcls(url=url, status=status, headers=headers, body=body,
- flags=flags, certificate=certificate)
++ flags=flags, certificate=certificate, ip_address=ip_address)
@implementer(IBodyProducer)
@@@ -457,12 -458,13 +459,17 @@@ class _ResponseReader(protocol.Protocol
self._fail_on_dataloss_warned = False
self._reached_warnsize = False
self._bytes_received = 0
+ self._certificate = None
+ self._ip_address = None
def connectionMade(self):
+ if self._certificate is None:
+ with suppress(AttributeError):
+ self._certificate = ssl.Certificate(self.transport._producer.getPeerCertificate())
+
+ if self._ip_address is None:
+ self._ip_address = ip_address(self.transport._producer.getPeer().host)
+
def dataReceived(self, bodyBytes):
# This maybe called several times after cancel was called with buffered data.
if self._finished.called:
@@@ -494,16 -496,16 +501,22 @@@
body = self._bodybuf.getvalue()
if reason.check(ResponseDone):
- self._finished.callback((self._txresponse, body, None, self._ip_address))
- self._finished.callback((self._txresponse, body, None, self._certificate))
++ self._finished.callback(
++ (self._txresponse, body, None, self._certificate, self._ip_address)
++ )
return
if reason.check(PotentialDataLoss):
- self._finished.callback((self._txresponse, body, ['partial'], self._ip_address))
- self._finished.callback((self._txresponse, body, ['partial'], self._certificate))
++ self._finished.callback(
++ (self._txresponse, body, ['partial'], self._certificate, self._ip_address)
++ )
return
if reason.check(ResponseFailed) and any(r.check(_DataLoss) for r in reason.value.reasons):
if not self._fail_on_dataloss:
- self._finished.callback((self._txresponse, body, ['dataloss'], self._ip_address))
- self._finished.callback((self._txresponse, body, ['dataloss'], self._certificate))
++ self._finished.callback(
++ (self._txresponse, body, ['dataloss'], self._certificate, self._ip_address)
++ )
return
elif not self._fail_on_dataloss_warned:
diff --cc scrapy/http/response/__init__.py
index ca5ecc02c,119dd2f63..1095cb87e
--- a/scrapy/http/response/__init__.py
+++ b/scrapy/http/response/__init__.py
@@@ -17,15 -17,25 +17,27 @@@ from scrapy.utils.trackref import objec
class Response(object_ref):
- def __init__(self, url, status=200, headers=None, body=b'', flags=None, request=None, ip_address=None):
- def __init__(self, url, status=200, headers=None, body=b'', flags=None, request=None, certificate=None):
++ def __init__(self, url, status=200, headers=None, body=b'', flags=None,
++ request=None, certificate=None, ip_address=None):
self.headers = Headers(headers or {})
self.status = int(status)
self._set_body(body)
self._set_url(url)
self.request = request
self.flags = [] if flags is None else list(flags)
+ self.certificate = certificate
+ self.ip_address = ip_address
+ @property
+ def cb_kwargs(self):
+ try:
+ return self.request.cb_kwargs
+ except AttributeError:
+ raise AttributeError(
+ "Response.cb_kwargs not available, this response "
+ "is not tied to any request"
+ )
+
@property
def meta(self):
try:
@@@ -77,7 -87,7 +89,8 @@@
"""Create a new Response with the same attributes except for those
given new values.
"""
- for x in ['url', 'status', 'headers', 'body', 'request', 'flags', 'ip_address']:
- for x in ['url', 'status', 'headers', 'body', 'request', 'flags', 'certificate']:
++ for x in ['url', 'status', 'headers', 'body',
++ 'request', 'flags', 'certificate', 'ip_address']:
kwargs.setdefault(x, getattr(self, x))
cls = kwargs.pop('cls', self.__class__)
return cls(*args, **kwargs)
diff --cc tests/test_crawl.py
index 3116eb88a,bbe97d034..3a9b00ab3
--- a/tests/test_crawl.py
+++ b/tests/test_crawl.py
@@@ -1,8 -1,6 +1,9 @@@
import json
import logging
+ import sys
+from ipaddress import IPv4Address
+from socket import gethostbyname
+from urllib.parse import urlparse
from pytest import mark
from testfixtures import LogCapture
@@@ -357,18 -409,30 +412,46 @@@ with multiples line
for req_id in range(3):
self.assertIn("Got response 200, req_id %d" % req_id, str(log))
+ @defer.inlineCallbacks
+ def test_response_ssl_certificate_none(self):
+ crawler = self.runner.create_crawler(SingleRequestSpider)
+ url = self.mockserver.url("/echo?body=test", is_secure=False)
+ yield crawler.crawl(seed=url, mockserver=self.mockserver)
+ self.assertIsNone(crawler.spider.meta['responses'][0].certificate)
+
+ @defer.inlineCallbacks
+ def test_response_ssl_certificate(self):
+ crawler = self.runner.create_crawler(SingleRequestSpider)
+ url = self.mockserver.url("/echo?body=test", is_secure=True)
+ yield crawler.crawl(seed=url, mockserver=self.mockserver)
+ cert = crawler.spider.meta['responses'][0].certificate
+ self.assertIsInstance(cert, Certificate)
+ self.assertEqual(cert.getSubject().commonName, b"localhost")
+ self.assertEqual(cert.getIssuer().commonName, b"localhost")
+
+ @mark.xfail(reason="Responses with no body return early and contain no certificate")
+ @defer.inlineCallbacks
+ def test_response_ssl_certificate_empty_response(self):
+ crawler = self.runner.create_crawler(SingleRequestSpider)
+ url = self.mockserver.url("/status?n=200", is_secure=True)
+ yield crawler.crawl(seed=url, mockserver=self.mockserver)
+ cert = crawler.spider.meta['responses'][0].certificate
+ self.assertIsInstance(cert, Certificate)
+ self.assertEqual(cert.getSubject().commonName, b"localhost")
+ self.assertEqual(cert.getIssuer().commonName, b"localhost")
++
+ @defer.inlineCallbacks
+ def test_dns_server_ip_address(self):
+ crawler = self.runner.create_crawler(SingleRequestSpider)
+ url = self.mockserver.url('/status?n=200')
+ yield crawler.crawl(seed=url, mockserver=self.mockserver)
+ ip_address = crawler.spider.meta['responses'][0].ip_address
+ self.assertIsNone(ip_address)
+
+ crawler = self.runner.create_crawler(SingleRequestSpider)
+ url = self.mockserver.url('/echo?body=test')
+ expected_netloc, _ = urlparse(url).netloc.split(':')
+ yield crawler.crawl(seed=url, mockserver=self.mockserver)
+ ip_address = crawler.spider.meta['responses'][0].ip_address
+ self.assertIsInstance(ip_address, IPv4Address)
+ self.assertEqual(str(ip_address), gethostbyname(expected_netloc))