Scrapy, a fast high-level web crawling & scraping framework for Python.
Response.follow
Mikhail Korobov2674f317df9e
diff --git a/scrapy/http/response/__init__.py b/scrapy/http/response/__init__.pyindex 58ad414f1..e5fb4eef8 100644--- a/scrapy/http/response/__init__.py+++ b/scrapy/http/response/__init__.py@@ -6,7 +6,9 @@ See documentation in docs/topics/request-response.rst"""from six.moves.urllib.parse import urljoin+from scrapy.http.request import Requestfrom scrapy.http.headers import Headers+from scrapy.link import Linkfrom scrapy.utils.trackref import object_reffrom scrapy.http.common import obsolete_setterfrom scrapy.exceptions import NotSupported@@ -101,3 +103,30 @@ class Response(object_ref):is text (subclasses of TextResponse)."""raise NotSupported("Response content isn't text")++ def follow(self, url, callback=None, method='GET', headers=None, body=None,+ cookies=None, meta=None, encoding='utf-8', priority=0,+ dont_filter=False, errback=None):+ # type: (...) -> Request+ """+ Return a scrapy.Request instance to follow a link ``url``.++ ``url`` can be:++ * absolute URL;+ * relative URL;+ * scrapy.link.Link object.+ """+ if isinstance(url, Link):+ url = url.url+ url = self.urljoin(url)+ return Request(url, callback,+ method=method,+ headers=headers,+ body=body,+ cookies=cookies,+ meta=meta,+ encoding=encoding,+ priority=priority,+ dont_filter=dont_filter,+ errback=errback)diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.pyindex 6eacfbd35..3c360bcf9 100644--- a/scrapy/http/response/text.py+++ b/scrapy/http/response/text.py@@ -140,25 +140,22 @@ class TextResponse(Response):* a Selector for ``<a>`` element, e.g.``response.css('a.my_link')[0]``."""- if isinstance(url, Link):- url = url.url- elif isinstance(url, parsel.Selector):+ if isinstance(url, parsel.Selector):url = _url_from_selector(url)elif isinstance(url, parsel.SelectorList):raise ValueError("SelectorList is not supported")-encoding = self.encoding if encoding is None else encoding- url = self.urljoin(url)- return Request(url, callback,- method=method,- headers=headers,- body=body,- cookies=cookies,- meta=meta,- encoding=encoding,- priority=priority,- dont_filter=dont_filter,- errback=errback)+ return super(TextResponse, self).follow(url, callback,+ method=method,+ headers=headers,+ body=body,+ cookies=cookies,+ meta=meta,+ encoding=encoding,+ priority=priority,+ dont_filter=dont_filter,+ errback=errback+ )def _url_from_selector(sel):diff --git a/tests/test_http_response.py b/tests/test_http_response.pyindex 2a9baf5ed..e64d0eeba 100644--- a/tests/test_http_response.py+++ b/tests/test_http_response.py@@ -143,6 +143,38 @@ class BaseResponseTest(unittest.TestCase):r.css('body')r.xpath('//body')+ def test_follow_url_absolute(self):+ self._assert_followed_url('http://foo.example.com',+ 'http://foo.example.com')++ def test_follow_url_relative(self):+ self._assert_followed_url('foo',+ 'http://example.com/foo')++ def test_follow_link(self):+ self._assert_followed_url(Link('http://example.com/foo'),+ 'http://example.com/foo')++ def test_follow_whitespace_url(self):+ self._assert_followed_url('foo ',+ 'http://example.com/foo%20')++ def test_follow_whitespace_link(self):+ self._assert_followed_url(Link('http://example.com/foo '),+ 'http://example.com/foo%20')++ def _assert_followed_url(self, follow_obj, target_url, response=None):+ if response is None:+ response = self._links_response()+ req = response.follow(follow_obj)+ self.assertEqual(req.url, target_url)+ return req++ def _links_response(self):+ body = get_testdata('link_extractor', 'sgml_linkextractor.html')+ resp = self.response_class('http://example.com/index', body=body)+ return resp+class TextResponseTest(BaseResponseTest):@@ -354,67 +386,6 @@ class TextResponseTest(BaseResponseTest):absolute = 'http://www.example.com/elsewhere/test'self.assertEqual(joined, absolute)--class HtmlResponseTest(TextResponseTest):-- response_class = HtmlResponse-- def _links_response(self):- body = get_testdata('link_extractor', 'sgml_linkextractor.html')- resp = self.response_class('http://example.com/index', body=body)- return resp-- def test_html_encoding(self):-- body = b"""<html><head><title>Some page</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">- </head><body>Price: \xa3100</body></html>'- """- r1 = self.response_class("http://www.example.com", body=body)- self._assert_response_values(r1, 'iso-8859-1', body)-- body = b"""<?xml version="1.0" encoding="iso-8859-1"?>- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">- Price: \xa3100- """- r2 = self.response_class("http://www.example.com", body=body)- self._assert_response_values(r2, 'iso-8859-1', body)-- # for conflicting declarations headers must take precedence- body = b"""<html><head><title>Some page</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8">- </head><body>Price: \xa3100</body></html>'- """- r3 = self.response_class("http://www.example.com", headers={"Content-type": ["text/html; charset=iso-8859-1"]}, body=body)- self._assert_response_values(r3, 'iso-8859-1', body)-- # make sure replace() preserves the encoding of the original response- body = b"New body \xa3"- r4 = r3.replace(body=body)- self._assert_response_values(r4, 'iso-8859-1', body)-- def test_html5_meta_charset(self):- body = b"""<html><head><meta charset="gb2312" /><title>Some page</title><body>bla bla</body>"""- r1 = self.response_class("http://www.example.com", body=body)- self._assert_response_values(r1, 'gb2312', body)-- def assert_followed_url(self, follow_obj, target_url, response=None):- if response is None:- response = self._links_response()- req = response.follow(follow_obj)- self.assertEqual(req.url, target_url)- return req-- def test_follow_url_absolute(self):- self.assert_followed_url('http://foo.example.com',- 'http://foo.example.com')-- def test_follow_url_relative(self):- self.assert_followed_url('foo',- 'http://example.com/foo')-- def test_follow_link(self):- self.assert_followed_url(Link('http://example.com/foo'),- 'http://example.com/foo')-def test_follow_selector(self):resp = self._links_response()urls = [@@ -428,12 +399,12 @@ class HtmlResponseTest(TextResponseTest):# select <a> elementsfor sellist in [resp.css('a'), resp.xpath('//a')]:for sel, url in zip(sellist, urls):- self.assert_followed_url(sel, url, response=resp)+ self._assert_followed_url(sel, url, response=resp)# href attributes should workfor sellist in [resp.css('a::attr(href)'), resp.xpath('//a/@href')]:for sel, url in zip(sellist, urls):- self.assert_followed_url(sel, url, response=resp)+ self._assert_followed_url(sel, url, response=resp)# non-a elements are not supportedself.assertRaises(ValueError, resp.follow, resp.css('div')[0])@@ -446,27 +417,19 @@ class HtmlResponseTest(TextResponseTest):def test_follow_selector_attribute(self):resp = self._links_response()for src in resp.css('img::attr(src)'):- self.assert_followed_url(src, 'http://example.com/sample2.jpg')-- def test_follow_whitespace_url(self):- self.assert_followed_url('foo ',- 'http://example.com/foo%20')-- def test_follow_whitespace_link(self):- self.assert_followed_url(Link('http://example.com/foo '),- 'http://example.com/foo%20')+ self._assert_followed_url(src, 'http://example.com/sample2.jpg')def test_follow_whitespace_selector(self):resp = self.response_class('http://example.com',body=b'''<html><body><a href=" foo\n">click me</a></body></html>''')- self.assert_followed_url(resp.css('a')[0],+ self._assert_followed_url(resp.css('a')[0],'http://example.com/foo',- response=resp)- self.assert_followed_url(resp.css('a::attr(href)')[0],+ response=resp)+ self._assert_followed_url(resp.css('a::attr(href)')[0],'http://example.com/foo',- response=resp)+ response=resp)def test_follow_encoding(self):resp1 = self.response_class(@@ -474,7 +437,7 @@ class HtmlResponseTest(TextResponseTest):encoding='utf8',body='<html><body><a href="foo?привет">click me</a></body></html>'.encode('utf8'))- req = self.assert_followed_url(+ req = self._assert_followed_url(resp1.css('a')[0],'http://example.com/foo?%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82',response=resp1,@@ -486,7 +449,7 @@ class HtmlResponseTest(TextResponseTest):encoding='cp1251',body='<html><body><a href="foo?привет">click me</a></body></html>'.encode('cp1251'))- req = self.assert_followed_url(+ req = self._assert_followed_url(resp2.css('a')[0],'http://example.com/foo?%EF%F0%E8%E2%E5%F2',response=resp2,@@ -494,6 +457,43 @@ class HtmlResponseTest(TextResponseTest):self.assertEqual(req.encoding, 'cp1251')+class HtmlResponseTest(TextResponseTest):++ response_class = HtmlResponse++ def test_html_encoding(self):++ body = b"""<html><head><title>Some page</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+ </head><body>Price: \xa3100</body></html>'+ """+ r1 = self.response_class("http://www.example.com", body=body)+ self._assert_response_values(r1, 'iso-8859-1', body)++ body = b"""<?xml version="1.0" encoding="iso-8859-1"?>+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">+ Price: \xa3100+ """+ r2 = self.response_class("http://www.example.com", body=body)+ self._assert_response_values(r2, 'iso-8859-1', body)++ # for conflicting declarations headers must take precedence+ body = b"""<html><head><title>Some page</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8">+ </head><body>Price: \xa3100</body></html>'+ """+ r3 = self.response_class("http://www.example.com", headers={"Content-type": ["text/html; charset=iso-8859-1"]}, body=body)+ self._assert_response_values(r3, 'iso-8859-1', body)++ # make sure replace() preserves the encoding of the original response+ body = b"New body \xa3"+ r4 = r3.replace(body=body)+ self._assert_response_values(r4, 'iso-8859-1', body)++ def test_html5_meta_charset(self):+ body = b"""<html><head><meta charset="gb2312" /><title>Some page</title><body>bla bla</body>"""+ r1 = self.response_class("http://www.example.com", body=body)+ self._assert_response_values(r1, 'gb2312', body)++class XmlResponseTest(TextResponseTest):response_class = XmlResponse