-
Notifications
You must be signed in to change notification settings - Fork 10.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[MRG] AjaxCrawlableMiddleware #343
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a87b3bd
AjaxCrawlableMiddleware
kmike 71c59e1
add an undocumented setting for lookup body size
kmike 503ab58
Fail-fast path.
kmike 84a3a9d
extra test
kmike 943a0bd
AjaxCrawlableMiddleware in Broad Crawl docs
kmike ee46ec8
kill AjaxCrawlableMiddlewar.enabled_setting
kmike e0cebbf
add a remark about 1%
kmike File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# -*- coding: utf-8 -*- | ||
from __future__ import absolute_import | ||
import re | ||
from scrapy import log | ||
from scrapy.exceptions import NotConfigured | ||
from scrapy.http import HtmlResponse | ||
from scrapy.utils.response import _noscript_re, _script_re | ||
from w3lib import html | ||
|
||
class AjaxCrawlableMiddleware(object): | ||
""" | ||
Handle 'AJAX crawlable' pages marked as crawlable via meta tag. | ||
For more info see https://developers.google.com/webmasters/ajax-crawling/docs/getting-started. | ||
""" | ||
|
||
enabled_setting = 'AJAXCRAWLABLE_ENABLED' | ||
|
||
def __init__(self, settings): | ||
if not settings.getbool(self.enabled_setting): | ||
raise NotConfigured | ||
|
||
# XXX: Google parses at least first 100k bytes; scrapy's redirect | ||
# middleware parses first 4k. 4k turns out to be insufficient | ||
# for this middleware, and parsing 100k could be slow. | ||
# We use something in between (32K) by default. | ||
self.lookup_bytes = settings.getint('AJAXCRAWLABLE_MAXSIZE', 32768) | ||
|
||
@classmethod | ||
def from_crawler(cls, crawler): | ||
return cls(crawler.settings) | ||
|
||
def process_response(self, request, response, spider): | ||
|
||
if not isinstance(response, HtmlResponse) or response.status != 200: | ||
return response | ||
|
||
if request.method != 'GET': | ||
# other HTTP methods are either not safe or don't have a body | ||
return response | ||
|
||
if 'ajax_crawlable' in request.meta: # prevent loops | ||
return response | ||
|
||
if not self._has_ajax_crawlable_variant(response): | ||
return response | ||
|
||
# scrapy already handles #! links properly | ||
ajax_crawlable = request.replace(url=request.url+'#!') | ||
log.msg(format="Downloading AJAX crawlable %(ajax_crawlable)s instead of %(request)s", | ||
level=log.DEBUG, spider=spider, ajax_crawlable=ajax_crawlable, | ||
request=request) | ||
|
||
ajax_crawlable.meta['ajax_crawlable'] = True | ||
return ajax_crawlable | ||
|
||
def _has_ajax_crawlable_variant(self, response): | ||
""" | ||
Return True if a page without hash fragment could be "AJAX crawlable" | ||
according to https://developers.google.com/webmasters/ajax-crawling/docs/getting-started. | ||
""" | ||
body = response.body_as_unicode()[:self.lookup_bytes] | ||
return _has_ajaxcrawlable_meta(body) | ||
|
||
|
||
# XXX: move it to w3lib? | ||
_ajax_crawlable_re = re.compile(ur'<meta\s+name=["\']fragment["\']\s+content=["\']!["\']/?>') | ||
def _has_ajaxcrawlable_meta(text): | ||
""" | ||
>>> _has_ajaxcrawlable_meta('<html><head><meta name="fragment" content="!"/></head><body></body></html>') | ||
True | ||
>>> _has_ajaxcrawlable_meta("<html><head><meta name='fragment' content='!'></head></html>") | ||
True | ||
>>> _has_ajaxcrawlable_meta('<html><head><!--<meta name="fragment" content="!"/>--></head><body></body></html>') | ||
False | ||
>>> _has_ajaxcrawlable_meta('<html></html>') | ||
False | ||
""" | ||
|
||
# Stripping scripts and comments is slow (about 20x slower than | ||
# just checking if a string is in text); this is a quick fail-fast | ||
# path that should work for most pages. | ||
if 'fragment' not in text: | ||
return False | ||
if 'content' not in text: | ||
return False | ||
|
||
text = _script_re.sub(u'', text) | ||
text = _noscript_re.sub(u'', text) | ||
text = html.remove_comments(html.remove_entities(text)) | ||
return _ajax_crawlable_re.search(text) is not None | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import unittest | ||
|
||
from scrapy.contrib.downloadermiddleware.ajaxcrawlable import AjaxCrawlableMiddleware | ||
from scrapy.spider import BaseSpider | ||
from scrapy.http import Request, HtmlResponse, Response | ||
from scrapy.utils.test import get_crawler | ||
|
||
__doctests__ = ['scrapy.contrib.downloadermiddleware.ajaxcrawlable'] | ||
|
||
class AjaxCrawlableMiddlewareTest(unittest.TestCase): | ||
def setUp(self): | ||
self.spider = BaseSpider('foo') | ||
crawler = get_crawler({'AJAXCRAWLABLE_ENABLED': True}) | ||
self.mw = AjaxCrawlableMiddleware.from_crawler(crawler) | ||
|
||
def _ajaxcrawlable_body(self): | ||
return '<html><head><meta name="fragment" content="!"/></head><body></body></html>' | ||
|
||
def _req_resp(self, url, req_kwargs=None, resp_kwargs=None): | ||
req = Request(url, **(req_kwargs or {})) | ||
resp = HtmlResponse(url, request=req, **(resp_kwargs or {})) | ||
return req, resp | ||
|
||
def test_non_get(self): | ||
req, resp = self._req_resp('http://example.com/', {'method': 'HEAD'}) | ||
resp2 = self.mw.process_response(req, resp, self.spider) | ||
self.assertEqual(resp, resp2) | ||
|
||
def test_binary_response(self): | ||
req = Request('http://example.com/') | ||
resp = Response('http://example.com/', body=b'foobar\x00\x01\x02', request=req) | ||
resp2 = self.mw.process_response(req, resp, self.spider) | ||
self.assertIs(resp, resp2) | ||
|
||
def test_ajax_crawlable(self): | ||
req, resp = self._req_resp( | ||
'http://example.com/', | ||
{'meta': {'foo': 'bar'}}, | ||
{'body': self._ajaxcrawlable_body()} | ||
) | ||
req2 = self.mw.process_response(req, resp, self.spider) | ||
self.assertEqual(req2.url, 'http://example.com/?_escaped_fragment_=') | ||
self.assertEqual(req2.meta['foo'], 'bar') | ||
|
||
def test_ajax_crawlable_loop(self): | ||
req, resp = self._req_resp('http://example.com/', {}, {'body': self._ajaxcrawlable_body()}) | ||
req2 = self.mw.process_response(req, resp, self.spider) | ||
resp2 = HtmlResponse(req2.url, body=resp.body, request=req2) | ||
resp3 = self.mw.process_response(req2, resp2, self.spider) | ||
|
||
assert isinstance(resp3, HtmlResponse), (resp3.__class__, resp3) | ||
self.assertEqual(resp3.request.url, 'http://example.com/?_escaped_fragment_=') | ||
assert resp3 is resp2 | ||
|
||
def test_noncrawlable_body(self): | ||
req, resp = self._req_resp('http://example.com/', {}, {'body': '<html></html>'}) | ||
resp2 = self.mw.process_response(req, resp, self.spider) | ||
self.assertIs(resp, resp2) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what is the advantage of using a class attribute for this settings instead of directly referencing it in the constructor like
AJAXCRAWLABLE_MAXSIZE
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No advantage. I blindly copied this code from MetaRefreshMiddleware (to make it consistent), but in MetaRefreshMiddleware it serves a purpose (MetaRefreshMiddleware is a subclass of BaseRedirectMiddleware and overrides this attribute), and here it is pointless. I'll fix it.