Created
August 14, 2014 22:04
-
-
Save nramirezuy/7a603cbc5cd381734df4 to your computer and use it in GitHub Desktop.
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
diff --git a/scrapy/selector/unified.py b/scrapy/selector/unified.py | |
index b8a3678..28d8ac9 100644 | |
--- a/scrapy/selector/unified.py | |
+++ b/scrapy/selector/unified.py | |
@@ -46,6 +46,38 @@ def _response_from_text(text, st): | |
body=unicode_to_str(text, 'utf-8')) | |
+class SelectorContext(object): | |
+ | |
+ def __init__(self): | |
+ self.stack = [] | |
+ | |
+ def open(self, selector): | |
+ self.stack.append(selector) | |
+ | |
+ def close(self): | |
+ self.stack.pop() | |
+ | |
+ def get_active(self): | |
+ if self.stack: | |
+ return self.stack[-1] | |
+ | |
+selector_context = SelectorContext() | |
+ | |
+ | |
+from functools import wraps | |
+ | |
+ | |
+def selectorcontext(func): | |
+ @wraps(func) | |
+ def wrapper(**kwargs): | |
+ if 'selector' not in kwargs: | |
+ selector = selector_context.get_active() | |
+ if selector is not None: | |
+ kwargs['selector'] = selector | |
+ return func(**kwargs) | |
+ return wrapper | |
+ | |
+ | |
class Selector(object_ref): | |
__slots__ = ['response', 'text', 'namespaces', 'type', '_expr', '_root', | |
@@ -85,6 +117,13 @@ class Selector(object_ref): | |
self._root = _root | |
self._expr = _expr | |
+ def __enter__(self): | |
+ selector_context.open(self) | |
+ return self | |
+ | |
+ def __exit__(self, type, value, traceback): | |
+ selector_context.close() | |
+ | |
def xpath(self, query): | |
try: | |
xpathev = self._root.xpath | |
@@ -166,7 +205,17 @@ class SelectorList(list): | |
def __getslice__(self, i, j): | |
return self.__class__(list.__getslice__(self, i, j)) | |
+ def __enter__(self): | |
+ selector_context.open(self) | |
+ return self | |
+ | |
+ def __exit__(self, type, value, traceback): | |
+ selector_context.close() | |
+ | |
def xpath(self, xpath): | |
+ selector = selector_context.get_active() | |
+ if selector: | |
+ return selector.xpath(xpath) | |
return self.__class__(flatten([x.xpath(xpath) for x in self])) | |
def css(self, xpath): |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment