Skip to content

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

Several modifications done: . attribute method moved from ScrapedItem to RobustScrapedItem . this method was also drastically changed. now it accepts *args and runs the adaptor pipeline for each value . many adaptors were changed to work with single values instead of lists (due to the previous point's change) . ExtractImageLinks adaptor was modified to make use of the HTMLImageLinkExtractor . adaptors were moved from contrib to contrib_exp . tests were updated

elpolillaf6021cad2cf6
diff --git a/scrapy/trunk/scrapy/contrib/adaptorpipeline.py b/scrapy/trunk/scrapy/contrib/adaptorpipeline.py
deleted file mode 100644
index 9bac76b31..000000000
--- a/scrapy/trunk/scrapy/contrib/adaptorpipeline.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from scrapy.item.adaptors import AdaptorPipe as BaseAdaptorPipe
-from scrapy.utils.serialization import serialize
-
-class DuplicatedAdaptorName(Exception): pass
-
-class _Adaptor(object):
- """
- Adaptors instances should be instantiated and used only
- inside the AdaptorPipe.
- """
- def __init__(self, function, match_function):
- self.basefunction = function
- self.match_function = match_function
- def __repr__(self):
- return self.basefunction.func_name
- def __call__(self, *args):
- return self.basefunction(*args)
-
-class AdaptorPipe(BaseAdaptorPipe):
-
- def __init__(self, attribute_names, adaptors=None):
- """
- If "adaptors" is given, constructs pipeline from this.
- "adaptors" is an ordered tuple of 2-elements tuples, each of which
- has the same parameters you give to the insertadaptor method, except
- 'after' and 'before', because you define the adaptors order in the tuple.
- Example:
- (
- (my_function, lambda x: x in my_list)
- ...
- )
- """
- self.__attribute_names = [ n for n in attribute_names ]
- self.__adaptorspipe = []
- self.pipes = {}
- if adaptors:
- for entry in adaptors:
- self.insertadaptor(compile_pipe=False, *entry)
- self._compile_pipe()
-
- @property
- def adaptors_names(self):
- _adaptors = []
- for a in self.__adaptorspipe:
- _adaptors.append(a.basefunction.func_name)
- return _adaptors
-
- def insertadaptor(self, function, match_function=lambda x: True, compile_pipe=True, after=None, before=None):
- """
- Inserts a "function" as an adaptor that will apply when match_function returns True (by
- default always apply)
- If "after" is given, inserts the adaptor after the already inserted adaptor
- of the name given in this parameter, If "before" is given, inserts it before
- the adaptor of the given name. "name" is the name of the adaptor.
- """
- if function.func_name in self.adaptors_names:
- raise DuplicatedAdaptorName(function.func_name)
- else:
- adaptor = _Adaptor(function, match_function)
- #by default append adaptor at end of pipe
- pos = len(self.adaptors_names)
- if after:
- pos = self.adaptors_names.index(after) + 1
- elif before:
- pos = self.adaptors_names.index(before)
- self.__adaptorspipe.insert(pos, adaptor)
- if compile_pipe:
- self._compile_pipe()
- return pos
-
- def removeadaptor(self, adaptorname):
- pos = self.adaptors_names.index(adaptorname)
- self.__adaptorspipe.pop(pos)
- self._compile_pipe()
-
- def _compile_pipe(self):
- for attrname in self.__attribute_names:
- adaptors_pipe = []
- for adaptor in self.__adaptorspipe:
- if adaptor.match_function(attrname):
- adaptors_pipe.append(adaptor)
- self.pipes[attrname] = adaptors_pipe
-
- def __repr__(self):
- return serialize(self.pipes, "pprint")
\ No newline at end of file
diff --git a/scrapy/trunk/scrapy/contrib/adaptors/__init__.py b/scrapy/trunk/scrapy/contrib/adaptors/__init__.py
deleted file mode 100644
index 915550df7..000000000
--- a/scrapy/trunk/scrapy/contrib/adaptors/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from scrapy.contrib.adaptors.extraction import extract, ExtractImages
-from scrapy.contrib.adaptors.markup import remove_tags, remove_root, Unquote
-from scrapy.contrib.adaptors.misc import to_unicode, clean_spaces, strip, drop_empty, canonicalize_urls, Delist, Regex
-from scrapy.utils.python import unique, flatten
diff --git a/scrapy/trunk/scrapy/contrib/adaptors/extraction.py b/scrapy/trunk/scrapy/contrib/adaptors/extraction.py
deleted file mode 100644
index 222186966..000000000
--- a/scrapy/trunk/scrapy/contrib/adaptors/extraction.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""
-Adaptors related with extraction of data
-"""
-
-import urlparse
-import re
-from scrapy import log
-from scrapy.http import Response
-from scrapy.utils.url import is_url
-from scrapy.utils.python import flatten
-from scrapy.xpath.selector import XPathSelector, XPathSelectorList
-
-def extract(locations, adaptor_args=None):
- """
- This adaptor tries to extract data from the given locations.
- Any XPathSelector in it will be extracted, and any other data
- will be added as-is to the result.
-
- If an XPathSelector is a text/cdata node, and `use_unquote`
- is True, that selector will be extracted using the `extract_unquoted`
- method; otherwise, the `extract` method will be used.
-
- Input: anything
- Output: list of extracted selectors plus anything else in the input
- """
- locations = flatten([locations])
- use_unquote = adaptor_args.get('use_unquote', True) if adaptor_args else True
-
- result = []
- for location in locations:
- if isinstance(location, XPathSelector):
- if location.xmlNode.type in ('text', 'cdata') and use_unquote:
- result.append(location.extract_unquoted())
- else:
- result.append(location.extract())
- else:
- result.append(location)
- return result
-
-class ExtractImages(object):
- """
- This adaptor may receive either an XPathSelector containing
- the desired locations for finding urls, a list of relative
- links to be resolved, or simply a link (relative or not).
-
- Input: XPathSelector, XPathSelectorList, iterable
- Output: list of unicodes
- """
- def __init__(self, response=None, base_url=None):
- BASETAG_RE = re.compile(r'<base\s+href\s*=\s*[\"\']\s*([^\"\'\s]+)\s*[\"\']', re.I)
-
- if response:
- match = BASETAG_RE.search(response.body.to_string()[0:4096])
- if match:
- self.base_url = match.group(1)
- else:
- self.base_url = response.url
- else:
- self.base_url = base_url
-
- if not self.base_url:
- log.msg('No base URL was found for ExtractImages adaptor, will only extract absolute URLs', log.WARNING)
-
- def extract_from_xpath(self, selector):
- ret = []
- if selector.xmlNode.type == 'element':
- if selector.xmlNode.name == 'a':
- children = selector.x('child::*')
- if len(children) > 1:
- ret.extend(selector.x('.//@href'))
- ret.extend(selector.x('.//@src'))
- elif len(children) == 1 and children[0].xmlNode.name == 'img':
- ret.extend(children.x('@src'))
- else:
- ret.extend(selector.x('@href'))
- elif selector.xmlNode.name == 'img':
- ret.extend(selector.x('@src'))
- elif selector.xmlNode.name == 'text':
- ret.extend(selector)
- else:
- ret.extend(selector.x('.//@href'))
- ret.extend(selector.x('.//@src'))
- ret.extend(selector.x('.//text()'))
- else:
- ret.append(selector)
-
- return ret
-
- def __call__(self, locations):
- if not locations:
- return []
- elif isinstance(locations, basestring):
- locations = [locations]
-
- rel_urls = []
- for location in flatten(locations):
- if isinstance(location, (XPathSelector, XPathSelectorList)):
- rel_urls.extend(self.extract_from_xpath(location))
- else:
- rel_urls.append(location)
- rel_urls = extract(rel_urls)
-
- if self.base_url:
- return [urlparse.urljoin(self.base_url, url) for url in rel_urls]
- else:
- return filter(rel_urls, is_url)
diff --git a/scrapy/trunk/scrapy/contrib/adaptors/markup.py b/scrapy/trunk/scrapy/contrib/adaptors/markup.py
deleted file mode 100644
index 1dc4c3573..000000000
--- a/scrapy/trunk/scrapy/contrib/adaptors/markup.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import re
-from scrapy.utils.markup import replace_tags, unquote_markup
-from scrapy.item.adaptors import adaptize
-
-def remove_tags(value):
- """
- Removes any tags found in each of the provided list's string.
- E.g:
- >> remove_tags(['<head>my header</head>', '<body>my <b>body</b></body>'])
- [u'my header', u'my body']
- Input: iterable with strings
- Output: list of unicodes
- """
- return [ replace_tags(v) for v in value ]
-
-def remove_root(value):
- """
- Input: iterable with strings
- Output: list of strings
- """
- def _remove_root(value):
- _remove_root_re = re.compile(r'^\s*<.*?>(.*)</.*>\s*$', re.DOTALL)
- m = _remove_root_re.search(value)
- if m:
- value = m.group(1)
- return unicode(value)
- return [ _remove_root(v) for v in value ]
-
-class Unquote(object):
- """
- Receives a list of strings, removes all of the
- CDATAs and entities (except the ones in CDATAs) the strings
- may have, and returns a new list.
-
- Input: iterable with strings
- Output: list of strings
- """
- def __init__(self, keep=None):
- self.keep = [] if keep is None else keep
-
- def __call__(self, value, keep=None):
- keep = keep if keep is not None else self.keep
- return [ unquote_markup(v, keep=keep) for v in value ]
diff --git a/scrapy/trunk/scrapy/contrib/item/models.py b/scrapy/trunk/scrapy/contrib/item/models.py
index 8488844fb..bb1dc472d 100644
--- a/scrapy/trunk/scrapy/contrib/item/models.py
+++ b/scrapy/trunk/scrapy/contrib/item/models.py
@@ -9,9 +9,11 @@ from pydispatch import dispatcher
from pprint import PrettyPrinter
from scrapy.item import ScrapedItem, ItemDelta
+from scrapy.item.adaptors import AdaptorPipe
from scrapy.spider import spiders
from scrapy.core import signals
from scrapy.core.exceptions import UsageError, DropItem
+from scrapy.utils.python import unique
class ValidationError(DropItem):
"""Indicates a data validation error"""
@@ -40,16 +42,17 @@ class RobustScrapedItem(ScrapedItem):
'guid': basestring, # a global unique identifier
'url': basestring, # the main URL where this item was scraped from
}
-
- def __init__(self, data=None):
+
+ def __init__(self, data=None, adaptors_dict=None):
super(RobustScrapedItem, self).__init__(data)
+ self.__dict__['_adaptors_dict'] = adaptors_dict or {}
self.__dict__['_version'] = None
def __getattr__(self, attr):
# Return None for valid attributes not set, raise AttributeError for invalid attributes
# Note that this method is called only when the attribute is not found in
# self.__dict__ or the class/instance methods.
- if attr in self.ATTRIBUTES:
+ if attr in self.ATTRIBUTES:
return None
else:
raise AttributeError(attr)
@@ -82,7 +85,7 @@ class RobustScrapedItem(ScrapedItem):
self.__dict__[attr] = value
self.__dict__['_version'] = None
-
+
def __delattr__(self, attr):
"""
Delete an attribute from the ScrapedItem instance if it exists.
@@ -93,30 +96,118 @@ class RobustScrapedItem(ScrapedItem):
self.__dict__['_version'] = None
else:
raise AttributeError("Attribute '%s' doesn't exist" % attr)
-
+
def __eq__(self, other):
if isinstance(other, type(self)):
return self.version == other.version
-
+
def __ne__(self, other):
return self.version != other.version
-
+
def __sub__(self, other):
return RobustItemDelta(other, self)
def __str__(self) :
return "%s: GUID=%s, url=%s" % ( self.__class__.__name__ , self.guid, self.url )
-
+
+ def _add_single_attributes(self, attrname, attrtype, attributes):
+ if len(attributes) == 1:
+ return attributes[0]
+
+ if attrtype is basestring:
+ return ''.join(attributes)
+ else:
+ raise NotImplementedError('You must override _add_single_attributes method in order to join %s values into a single value.' % attrtype.__name__)
+
+ def _clean_values(self, values):
+ ret = []
+ for val in values:
+ if isinstance(val, tuple):
+ ret.extend(val)
+ elif val:
+ ret.append(val)
+ return ret
+
+ def attribute(self, attrname, *values, **kwargs):
+ """
+ Set the provided values to the provided attribute (`attrname`) by filtering them
+ through its adaptor pipeline first (if any).
+
+ If the attribute had been already set, it won't be overwritten unless the parameters
+ `override` or `add` are True.
+
+ If `override` is True, the old value simply will be replaced with the new one.
+
+ If add is True (and there was an old value, of course), for multivalued attributes the values
+ will be appended to the list of the already existing ones.
+ For this same situation in single-valued attributes, the method _add_single_attributes will be
+ called with the attribute's name and type, and the list of values to join as parameters.
+
+ The kwargs parameter is passed to the adaptors pipeline, which manages to transmit
+ it to the adaptors themselves.
+ """
+ if not values:
+ raise UsageError("You must specify at least one value when setting an attribute")
+ if attrname not in self.ATTRIBUTES:
+ raise AttributeError('Attribute "%s" is not a valid attribute name. You must add it to %s.ATTRIBUTES' % (attrname, self.__class__.__name__))
+
+ add = kwargs.pop('add', False)
+ override = kwargs.pop('override', False)
+ unique_vals = kwargs.pop('unique', False)
+ old_value = getattr(self, attrname, None)
+ if old_value and not any([override, add]):
+ return
+
+ attrtype = self.ATTRIBUTES.get(attrname)
+ multivalued = isinstance(attrtype, list)
+ adaptors_pipe = self._adaptors_dict.get(attrname)
+ new_values = [adaptors_pipe(value, kwargs) for value in values] if adaptors_pipe else [values]
+ new_values = self._clean_values(new_values)
+
+ if old_value and not override:
+ if multivalued:
+ new_values = old_value + new_values
+ else:
+ new_values.insert(0, old_value)
+
+ if not multivalued:
+ if add and len(new_values) >= 1:
+ new_values = self._add_single_attributes(attrname, attrtype, new_values)
+ else:
+ new_values = new_values[0] if new_values else None
+ elif multivalued and unique_vals:
+ new_values = unique(new_values)
+
+ setattr(self, attrname, new_values)
+
+ def set_attrib_adaptors(self, attrib, pipe):
+ """ Set the adaptors (from a list or tuple) to be used for a specific attribute. """
+ self._adaptors_dict[attrib] = pipe if isinstance(pipe, AdaptorPipe) else AdaptorPipe(pipe)
+
+ def set_adaptors(self, adaptors_dict):
+ """
+ Set the adaptors to use for this item. Receives a dict of the adaptors
+ desired for each attribute and returns the item itself.
+ """
+ self._adaptors_dict = {}
+ for attrib, pipe in adaptors_dict.items():
+ self.set_attrib_adaptors(attrib, pipe)
+ return self
+
+ def add_adaptor(self, attrib, adaptor, position=None):
+ """
+ Add an adaptor for the specified attribute at the given position.
+ If position = None, then the adaptor is appended at the end of the pipeline.
+ """
+ pipe = self._adaptors_dict.get(attrib, AdaptorPipe([]))
+ pipe.add_adaptor(adaptor, position)
+ self.set_attrib_adaptors(attrib, pipe)
+
def validate(self):
"""Method used to validate item attributes data"""
if not self.guid:
raise ValidationError('A guid is required')
- def copy(self):
- """Create a new ScrapedItem object based on the current one"""
- import copy
- return copy.deepcopy(self)
-
@property
def version(self):
"""
@@ -164,7 +255,7 @@ class RobustItemDelta(ItemDelta):
'attrib3': [{'new': 'New list value', 'old': 'Old list value'}, # List attributes
{'new': 'New list value 2', 'old': 'Old list value 2'}]}
"""
-
+
if self.old_item == self.new_item:
return {}
@@ -179,7 +270,7 @@ class RobustItemDelta(ItemDelta):
if not getattr(self.old_item, key):
diff[key] = {'new': value, 'old': None}
return diff
-
+
def __eq__(self, other):
if isinstance(other, RobustItemDelta):
if other.old_item == self.old_item and \
diff --git a/scrapy/trunk/scrapy/contrib_exp/__init__.py b/scrapy/trunk/scrapy/contrib_exp/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/scrapy/trunk/scrapy/contrib_exp/adaptors/__init__.py b/scrapy/trunk/scrapy/contrib_exp/adaptors/__init__.py
new file mode 100644
index 000000000..030020bc1
--- /dev/null
+++ b/scrapy/trunk/scrapy/contrib_exp/adaptors/__init__.py
@@ -0,0 +1,4 @@
+from scrapy.contrib_exp.adaptors.extraction import extract, ExtractImageLinks
+from scrapy.contrib_exp.adaptors.markup import remove_tags, remove_root, Unquote
+from scrapy.contrib_exp.adaptors.misc import to_unicode, clean_spaces, strip, drop_empty, Delist, Regex
+from scrapy.utils.python import flatten
diff --git a/scrapy/trunk/scrapy/contrib_exp/adaptors/extraction.py b/scrapy/trunk/scrapy/contrib_exp/adaptors/extraction.py
new file mode 100644
index 000000000..7e309be0b
--- /dev/null
+++ b/scrapy/trunk/scrapy/contrib_exp/adaptors/extraction.py
@@ -0,0 +1,78 @@
+"""
+Adaptors related with extraction of data
+"""
+
+import urlparse
+import re
+from scrapy import log
+from scrapy.http import Response
+from scrapy.utils.url import is_url
+from scrapy.utils.response import get_base_url
+from scrapy.utils.python import flatten, unicode_to_str
+from scrapy.xpath.selector import XPathSelector, XPathSelectorList
+from scrapy.contrib.link_extractors import HTMLImageLinkExtractor
+
+def extract(location, adaptor_args=None):
+ """
+ This adaptor tries to extract data from the given locations.
+ Any XPathSelector in it will be extracted, and any other data
+ will be added as-is to the result.
+
+ If an XPathSelector is a text/cdata node, and `use_unquote`
+ is True, that selector will be extracted using the `extract_unquoted`
+ method; otherwise, the `extract` method will be used.
+
+ Input: anything
+ Output: tuple of extracted selectors plus anything else in the input
+ """
+ use_unquote = adaptor_args.get('use_unquote', True) if adaptor_args else True
+
+ if isinstance(location, XPathSelectorList):
+ ret = location.extract()
+ elif isinstance(location, XPathSelector):
+ if location.xmlNode.type in ('text', 'cdata') and use_unquote:
+ ret = location.extract_unquoted()
+ else:
+ ret = location.extract()
+ ret = ret if hasattr(ret, '__iter__') else [ret]
+ elif isinstance(location, list):
+ ret = tuple(location)
+ else:
+ ret = tuple([location])
+
+ return tuple(x for x in ret if x is not None)
+
+class ExtractImageLinks(object):
+ """
+ This adaptor may receive either XPathSelectors pointing to
+ the desired locations for finding image urls, or just a list of
+ XPath expressions (which will be turned into selectors anyway).
+
+ Input: XPathSelector, XPathSelectorList, iterable
+ Output: tuple of urls (strings)
+ """
+ def __init__(self, response=None, canonicalize=True):
+ self.response = response
+ self.canonicalize = canonicalize
+
+ def __call__(self, locations):
+ if not locations:
+ return tuple()
+ elif not hasattr(locations, '__iter__'):
+ locations = [locations]
+
+ selectors, raw_links = [], []
+ for location in locations:
+ if isinstance(location, (XPathSelector, XPathSelectorList)):
+ selectors.append(location)
+ else:
+ raw_links.append(location)
+
+ if raw_links:
+ base_url = get_base_url(self.response)
+ raw_links = [urlparse.urljoin(base_url, unicode_to_str(rel_url)) for rel_url in raw_links]
+
+ lx = HTMLImageLinkExtractor(locations=selectors, canonicalize=self.canonicalize)
+ urls = map(lambda link: link.url, lx.extract_links(self.response))
+ return tuple(urls + raw_links)
+
diff --git a/scrapy/trunk/scrapy/contrib_exp/adaptors/markup.py b/scrapy/trunk/scrapy/contrib_exp/adaptors/markup.py
new file mode 100644
index 000000000..f376441cd
--- /dev/null
+++ b/scrapy/trunk/scrapy/contrib_exp/adaptors/markup.py
@@ -0,0 +1,42 @@
+import re
+from scrapy.utils.markup import replace_tags, unquote_markup
+from scrapy.utils.python import str_to_unicode
+from scrapy.item.adaptors import adaptize
+
+def remove_tags(value):
+ """
+ Removes any tags found in each of the provided list's string.
+ E.g:
+ >> remove_tags('<head>my header</head>', '<body>my <b>body</b></body>')
+ u'my header', u'my body'
+ Input: string/unicode
+ Output: unicode
+ """
+ return replace_tags(value)
+
+_remove_root_re = re.compile(r'^\s*<.*?>(.*)</.*>\s*$', re.DOTALL)
+def remove_root(value):
+ """
+ Input: string/unicode
+ Output: unicode
+ """
+ m = _remove_root_re.search(value)
+ if m:
+ value = m.group(1)
+ return str_to_unicode(value)
+
+class Unquote(object):
+ """
+ Receives a list of strings, removes all of the
+ CDATAs and entities (except the ones in CDATAs) the strings
+ may have, and returns a new list.
+
+ Input: string/unicode
+ Output: string/unicode
+ """
+ def __init__(self, keep=None):
+ self.keep = [] if keep is None else keep
+
+ def __call__(self, value, adaptor_args):
+ keep = adaptor_args.get('keep_entities', self.keep)
+ return unquote_markup(value, keep=keep)
diff --git a/scrapy/trunk/scrapy/contrib/adaptors/misc.py b/scrapy/trunk/scrapy/contrib_exp/adaptors/misc.py
similarity index 59%
rename from scrapy/trunk/scrapy/contrib/adaptors/misc.py
rename to scrapy/trunk/scrapy/contrib_exp/adaptors/misc.py
index 22e392385..634420307 100644
--- a/scrapy/trunk/scrapy/contrib/adaptors/misc.py
+++ b/scrapy/trunk/scrapy/contrib_exp/adaptors/misc.py
@@ -2,12 +2,11 @@
import re
from scrapy.xpath.selector import XPathSelector, XPathSelectorList
-from scrapy.utils.url import canonicalize_url
from scrapy.utils.misc import extract_regex
from scrapy.utils.python import flatten, str_to_unicode, unicode_to_str
from scrapy.item.adaptors import adaptize
-def to_unicode(value):
+def to_unicode(value, adaptor_args):
"""
Receives a list of strings, converts
it to unicode, and returns a new list.
@@ -18,11 +17,11 @@ def to_unicode(value):
Input: iterable of strings
Output: list of unicodes
"""
- if hasattr(value, '__iter__'):
- return [ str_to_unicode(v) if isinstance(v, basestring) else str_to_unicode(str(v)) for v in value ]
- else:
- raise TypeError('to_unicode must receive an iterable.')
+ if not isinstance(value, basestring):
+ value = str(value)
+ return str_to_unicode(value, adaptor_args.get('encoding', 'utf-8'))
+_clean_spaces_re = re.compile("\s+", re.U)
def clean_spaces(value):
"""
Converts multispaces into single spaces for each string
@@ -34,26 +33,20 @@ def clean_spaces(value):
Input: iterable of unicodes
Output: list of unicodes
"""
- _clean_spaces_re = re.compile("\s+", re.U)
- return [ _clean_spaces_re.sub(' ', str_to_unicode(v)) for v in value ]
+ return _clean_spaces_re.sub(' ', str_to_unicode(value))
def strip(value):
"""
Removes any spaces at both the start and the ending
- of the provided string or list.
+ of the provided string.
E.g:
- >> strip([' hi ', 'buddies '])
- [u'hi', u'buddies']
>> strip(' hi buddies ')
u'hi buddies'
- Input: unicode or iterable of unicodes
- Output: unicode or list of unicodes
+ Input: string/unicode
+ Output: string/unicode
"""
- if isinstance(value, basestring):
- return unicode(value.strip())
- elif hasattr(value, '__iter__'):
- return [ unicode(v.strip()) for v in value ]
+ return value.strip()
def drop_empty(value):
"""
@@ -68,36 +61,20 @@ def drop_empty(value):
"""
return [ v for v in value if v ]
-def canonicalize_urls(value):
- """
- Canonicalizes each url in the list you provide.
- To see what this implies, check out canonicalize_url's
- docstring, at scrapy.utils.url.py
-
- Input: iterable of unicodes(urls)
- Output: list of unicodes(urls)
- """
- if hasattr(value, '__iter__'):
- return [canonicalize_url(unicode_to_str(url)) for url in value]
- elif isinstance(value, basestring):
- return canonicalize_url(unicode_to_str(value))
- return ''
-
class Delist(object):
"""
Joins a list with the specified delimiter
in the adaptor's constructor.
- Input: iterable of strings
- Output: unicode
+ Input: iterable of strings/unicodes
+ Output: string/unicode
"""
- def __init__(self, delimiter=' '):
+ def __init__(self, delimiter=''):
self.delimiter = delimiter
-
- def __call__(self, value, delimiter=None):
- if delimiter is not None:
- self.delimiter = delimiter
- return self.delimiter.join(value)
+
+ def __call__(self, value, adaptor_args):
+ delimiter = adaptor_args.get('join_delimiter', self.delimiter)
+ return delimiter.join(value)
class Regex(object):
"""
diff --git a/scrapy/trunk/scrapy/item/adaptors.py b/scrapy/trunk/scrapy/item/adaptors.py
index 162247e48..85efee190 100644
--- a/scrapy/trunk/scrapy/item/adaptors.py
+++ b/scrapy/trunk/scrapy/item/adaptors.py
@@ -3,6 +3,38 @@ import inspect
from traceback import format_exc
from scrapy.conf import settings
+class AdaptorFunc(object):
+ """
+ This is a private class that the AdaptorPipe uses to store
+ its adaptation functions and their attributes.
+ """
+ def __init__(self, adaptor):
+ self.adaptor = adaptor
+
+ if inspect.isfunction(adaptor):
+ self.func_args, _, _, _ = inspect.getargspec(adaptor)
+ elif hasattr(adaptor, '__call__'):
+ try:
+ self.func_args, _, _, _ = inspect.getargspec(adaptor.__call__)
+ except Exception:
+ self.func_args = []
+
+ self.name = getattr(adaptor, 'func_name', None)
+ if not self.name:
+ if hasattr(adaptor, '__class__') and adaptor.__class__ is not type:
+ self.name = adaptor.__class__.__name__
+ else:
+ self.name = adaptor.__name__
+
+ def __call__(self, value, kwargs):
+ if 'adaptor_args' in self.func_args:
+ return self.adaptor(value, kwargs)
+ else:
+ return self.adaptor(value)
+
+ def __repr__(self):
+ return '<Adaptor %s >' % self.name
+
class AdaptorPipe(list):
"""
Class that represents an item's attribute pipeline.
@@ -11,44 +43,46 @@ class AdaptorPipe(list):
in order to filter the input.
"""
def __init__(self, adaptors):
+ def _filter_adaptor(adaptor):
+ return AdaptorFunc(adaptor) if not isinstance(adaptor, AdaptorFunc) else adaptor
+
+ if not hasattr(adaptors, '__iter__'):
+ raise TypeError('You must provide AdaptorPipe a list of adaptors')
+
for adaptor in adaptors:
if not callable(adaptor):
raise TypeError("%s is not a callable" % adaptor)
- super(AdaptorPipe, self).__init__(adaptors)
+ super(AdaptorPipe, self).__init__(map(_filter_adaptor, adaptors))
self.debug = settings.getbool('ADAPTORS_DEBUG')
- def __call__(self, value, **kwargs):
+ def __call__(self, value, kwargs=None):
"""
Execute the adaptor pipeline for this attribute.
"""
+ values = [value]
for adaptor in self:
- if inspect.isfunction(adaptor):
- func_args, _, _ ,_ = inspect.getargspec(adaptor)
- else:
- func_args = []
+ next_round = []
+ for val in values:
+ try:
+ if self.debug:
+ print " %07s | input >" % adaptor.name, repr(val)
- name = getattr(adaptor, 'func_name', None)
- if not name:
- name = adaptor.__class__.__name__ if hasattr(adaptor, '__class__') else adaptor.__name__
+ val = adaptor(val, kwargs or {})
+ if isinstance(val, tuple):
+ next_round.extend(val)
+ else:
+ next_round.append(val)
- try:
- if self.debug:
- print " %07s | input >" % name, repr(value)
+ if self.debug:
+ print " %07s | output >" % adaptor.name, repr(val)
+ except Exception:
+ print "Error in '%s' adaptor. Traceback text:" % adaptor.name
+ print format_exc()
+ return
+ values = next_round
- if 'adaptor_args' in func_args:
- value = adaptor(value, kwargs)
- else:
- value = adaptor(value)
-
- if self.debug:
- print " %07s | output >" % name, repr(value)
- except Exception:
- print "Error in '%s' adaptor. Traceback text:" % name
- print format_exc()
- return
-
- return value
+ return tuple(values)
def __add__(self, other):
if callable(other):
@@ -60,6 +94,15 @@ class AdaptorPipe(list):
def __repr__(self):
return '<AdaptorPipe %s >' % super(AdaptorPipe, self).__repr__()
+ def add_adaptor(self, adaptor, position=None):
+ if callable(adaptor):
+ if not isinstance(adaptor, AdaptorFunc):
+ adaptor = AdaptorFunc(adaptor)
+ if position is None:
+ self.append(adaptor)
+ else:
+ self.insert(position, adaptor)
+
def adaptize(adaptor, my_args=None):
"""
This decorator helps you add to your pipelines adaptors that are able
diff --git a/scrapy/trunk/scrapy/item/models.py b/scrapy/trunk/scrapy/item/models.py
index 4fb13ebb0..9212e0282 100644
--- a/scrapy/trunk/scrapy/item/models.py
+++ b/scrapy/trunk/scrapy/item/models.py
@@ -1,5 +1,4 @@
-from scrapy.conf import settings
-from scrapy.item.adaptors import AdaptorPipe
+import copy
class ScrapedItem(object):
"""
@@ -13,8 +12,6 @@ class ScrapedItem(object):
A ScrapedItem can be initialised with a dictionary that will be
squirted directly into the object.
"""
- self._adaptors_dict = {}
-
if isinstance(data, dict):
for attr, value in data.iteritems():
setattr(self, attr, value)
@@ -32,69 +29,9 @@ class ScrapedItem(object):
def __sub__(self, other):
raise NotImplementedError
- def set_adaptors(self, adaptors_dict):
- """
- Set the adaptors to use for this item. Receives a dict of the adaptors
- desired for each attribute and returns the item itself.
- """
- _adaptors_dict = dict((attrib, AdaptorPipe(pipe)) for attrib, pipe in adaptors_dict.items() if hasattr(pipe, '__iter__'))
- self.__dict__['_adaptors_dict'] = _adaptors_dict
- return self
-
- def set_attrib_adaptors(self, attrib, pipe):
- """ Set the adaptors (from a list or tuple) to be used for a specific attribute. """
- self._adaptors_dict[attrib] = AdaptorPipe(pipe) if hasattr(pipe, '__iter__') else None
-
- def add_adaptor(self, attrib, adaptor, position=None):
- """
- Add an adaptor for the specified attribute at the given position.
- If position = None, then the adaptor is appended at the end of the pipeline.
- """
- if callable(adaptor):
- pipe = self._adaptors_dict.get(attrib, [])
- if position is None:
- pipe = pipe + [adaptor]
- else:
- pipe.insert(position, adaptor)
- self.set_attrib_adaptors(attrib, pipe)
-
- def attribute(self, attrname, value, override=False, add=False, **kwargs):
- """
- Set the given value to the provided attribute (`attrname`) by filtering it
- through its adaptor pipeline first (if it has any).
-
- If the attribute has been already set, it won't be overwritten unless
- `override` is True.
- If there was an old value and `add` is True (but `override` isn't), `value`
- will be appended/extended (depending on its type), to the old value, as long as
- the old value is a list.
- If both of the values are strings they will be joined by using the `add` delimiter
- (which may be a string, or True, in which case '' will be used as the delimiter).
-
- The kwargs parameter is passed to the adaptors pipeline, which manages to transmit
- it to the adaptors themselves.
- """
- pipe = self._adaptors_dict.get(attrname)
- old_value = getattr(self, attrname, None)
-
- if pipe:
- value = pipe(value, **kwargs)
-
- if old_value:
- if override:
- setattr(self, attrname, value)
- elif add:
- if hasattr(old_value, '__iter__'):
- if hasattr(value, '__iter__'):
- self.__dict__[attrname].extend(list(value))
- else:
- self.__dict__[attrname].append(value)
- elif isinstance(old_value, basestring) and isinstance(value, basestring):
- delimiter = add if isinstance(add, basestring) else ''
- setattr(self, attrname, '%s%s%s' % (old_value, delimiter, value))
- else:
- setattr(self, attrname, value)
-
+ def copy(self):
+ """Create a new ScrapedItem based on the current one"""
+ return copy.deepcopy(self)
class ItemDelta(object):
pass
diff --git a/scrapy/trunk/scrapy/tests/test_adaptors.py b/scrapy/trunk/scrapy/tests/test_adaptors.py
index af5f00ed7..0d779794f 100644
--- a/scrapy/trunk/scrapy/tests/test_adaptors.py
+++ b/scrapy/trunk/scrapy/tests/test_adaptors.py
@@ -4,9 +4,10 @@ import unittest
import re
from scrapy.item.adaptors import AdaptorPipe
-from scrapy.contrib import adaptors
+from scrapy.contrib_exp import adaptors
from scrapy.http import Response, Headers
from scrapy.xpath.selector import HtmlXPathSelector, XmlXPathSelector
+from scrapy.link import Link
class AdaptorPipeTestCase(unittest.TestCase):
def test_pipe_init(self):
@@ -20,9 +21,9 @@ class AdaptorPipeTestCase(unittest.TestCase):
sample_value = 'hi, this is my text:'
sample_pipe = AdaptorPipe([sample_adaptor])
- self.assertEqual(sample_pipe(sample_value), 'hi, this is my text: "sample text 1"')
- self.assertEqual(sample_pipe(sample_value, sample_arg='foobarfoobar'),
- 'hi, this is my text: "foobarfoobar"')
+ self.assertEqual(sample_pipe(sample_value), ('hi, this is my text: "sample text 1"', ))
+ self.assertEqual(sample_pipe(sample_value, {'sample_arg': 'foobarfoobar'}),
+ ('hi, this is my text: "foobarfoobar"', ))
def test_add(self):
pipe1 = AdaptorPipe([adaptors.extract])
@@ -51,21 +52,21 @@ class AdaptorsTestCase(unittest.TestCase):
eurore = re.compile(r'<span class="euro" .*?>(.*?)</span>')
if pound:
- self.assertEqual(adaptors.extract(x.x("//span[@class='pound']/text()")), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='pound']/@value")), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.re(poundre)), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='poundent']/text()")), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='poundent']/@value")), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='poundnum']/text()")), [u'\xa3'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='poundnum']/@value")), [u'\xa3'])
+ self.assertEqual(adaptors.extract(x.x("//span[@class='pound']/text()")), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='pound']/@value")), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.re(poundre)), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='poundent']/text()")), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='poundent']/@value")), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='poundnum']/text()")), (u'\xa3', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='poundnum']/@value")), (u'\xa3', ))
if euro:
- self.assertEqual(adaptors.extract(x.x("//span[@class='euro']/text()")), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='euro']/@value")), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.re(eurore)), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='euroent']/text()")), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='euroent']/@value")), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='euronum']/text()")), [u'\u20ac'])
- self.assertEqual(adaptors.extract(x.x("//span[@class='euronum']/@value")), [u'\u20ac'])
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euro']/text()")), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euro']/@value")), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.re(eurore)), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euroent']/text()")), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euroent']/@value")), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euronum']/text()")), (u'\u20ac', ))
+ self.assertEqual(adaptors.extract(x.x("//span[@class='euronum']/@value")), (u'\u20ac', ))
x = self.get_selector('example.com',
'http://www.example.com/test/utf8',
@@ -105,15 +106,15 @@ class AdaptorsTestCase(unittest.TestCase):
x = self.get_selector('example.com', 'http://www.example.com/test_unquoted', 'extr_unquoted.xml', selector=XmlXPathSelector)
# test unquoting
- self.assertEqual(adaptors.extract(x.x('//tag1/text()')), [u'test text & &', u'more test text &amp; &gt;', u'blah&blah'])
- self.assertEqual(adaptors.extract(x.x('//tag2/text()')), [u'blaheawfds<'])
+ self.assertEqual(adaptors.extract(x.x('//tag1/text()[2]')[0]), (u'more test text &amp; &gt;', ))
+ self.assertEqual(adaptors.extract(x.x('//tag2/text()[1]')[0]), (u'blaheawfds<', ))
# test without unquoting
self.assertEqual(adaptors.extract(x.x('//tag1/text()'), {'use_unquote': False}),
- [u'test text &amp; &amp;', u'<![CDATA[more test text &amp; &gt;]]>', u'blah&amp;blah'])
- self.assertEqual(adaptors.extract(x.x('//tag2/text()'), {'use_unquote': False}), [u'blaheawfds&lt;'])
+ (u'test text &amp; &amp;', u'<![CDATA[more test text &amp; &gt;]]>', u'blah&amp;blah'))
+ self.assertEqual(adaptors.extract(x.x('//tag2/text()'), {'use_unquote': False}), (u'blaheawfds&lt;', ))
- def test_extract_links(self):
+ def test_extract_image_links(self):
test_data = """<html><body>
<div>
<a href="lala1/lala1.html">lala1</a>
@@ -125,26 +126,34 @@ class AdaptorsTestCase(unittest.TestCase):
</div>
</body></html>"""
sample_response = Response('http://foobar.com/dummy', body=test_data)
- sample_xsel = XmlXPathSelector(sample_response)
- sample_adaptor = adaptors.ExtractImages(response=sample_response)
-
- self.assertEqual(sample_adaptor(None), [])
- self.assertEqual(sample_adaptor([]), [])
- self.assertEqual(sample_adaptor('http://foobar.com/my_image.jpg'), ['http://foobar.com/my_image.jpg'])
- self.assertEqual(sample_adaptor([sample_xsel.x('//@href'), 'my_image.gif']),
- [u'http://foobar.com/lala1/lala1.html', u'http://foobar.com/lala2.html',
- u'http://foobar.com/pepepe/papapa/lala3.html', u'http://foobar.com/lala4.html', u'http://foobar.com/my_image.gif'])
- self.assertEqual(sample_adaptor(sample_xsel.x('//a')),
- [u'http://foobar.com/lala1/lala1.html', u'http://foobar.com/lala2.html',
- u'http://foobar.com/pepepe/papapa/lala3.html', u'http://foobar.com/imgs/lala4.jpg'])
- self.assertEqual(sample_adaptor(sample_xsel.x('//a[@onclick]').re(r'opensomething\(\'(.*?)\'\)')),
- [u'http://foobar.com/my_html1.html', u'http://foobar.com/dummy/my_html2.html'])
-
+ sample_selector = HtmlXPathSelector(sample_response)
+ sample_adaptor = adaptors.ExtractImageLinks(response=sample_response)
+
+ self.assertEqual(sample_adaptor(None), tuple())
+ self.assertEqual(sample_adaptor([]), tuple())
+ self.assertEqual(sample_adaptor([sample_selector.x('//@href'), 'http://foobar.com/my_image.gif']), (
+ 'http://foobar.com/lala1/lala1.html',
+ 'http://foobar.com/lala2.html',
+ 'http://foobar.com/pepepe/papapa/lala3.html',
+ 'http://foobar.com/lala4.html',
+ 'http://foobar.com/my_image.gif',
+ ))
+ self.assertEqual(sample_adaptor(sample_selector.x('//a')), (
+ 'http://foobar.com/lala1/lala1.html',
+ 'http://foobar.com/lala2.html',
+ 'http://foobar.com/pepepe/papapa/lala3.html',
+ 'http://foobar.com/imgs/lala4.jpg',
+ ))
+ self.assertEqual(sample_adaptor(sample_selector.x('//a[@onclick]').re(r'opensomething\(\'(.*?)\'\)')), (
+ 'http://foobar.com/my_html1.html',
+ 'http://foobar.com/dummy/my_html2.html'
+ ))
def test_to_unicode(self):
- self.assertEqual(adaptors.to_unicode(['lala', 'lele', 'lulu\xc3\xb1', 1, '\xc3\xa1\xc3\xa9']),
- [u'lala', u'lele', u'lulu\xf1', u'1', u'\xe1\xe9'])
-
+ self.assertEqual(adaptors.to_unicode('lelelulu\xc3\xb1', {}), u'lelelulu\xf1')
+ self.assertEqual(adaptors.to_unicode(1, {}), u'1')
+ self.assertEqual(adaptors.to_unicode('\xc3\xa1\xc3\xa9', {'encoding': 'utf-8'}), u'\xe1\xe9')
+ self.assertEqual(adaptors.to_unicode('\xf1', {'encoding': 'latin1'}), u'\xf1')
def test_regex(self):
adaptor = adaptors.Regex(regex=r'href="(.*?)"')
@@ -152,44 +161,40 @@ class AdaptorsTestCase(unittest.TestCase):
'<a href="das.biz">href="lelelel.net"</a>']),
['lala.com', 'pepe.co.uk', 'das.biz', 'lelelel.net'])
-
def test_unquote_all(self):
- self.assertEqual(adaptors.Unquote()([u'hello&copy;&amp;welcome', u'&lt;br /&gt;&amp;']), [u'hello\xa9&welcome', u'<br />&'])
-
+ unquote = adaptors.Unquote()
+ self.assertEqual(unquote(u'hello&copy;&amp;welcome&lt;br /&gt;&amp;', {}),
+ u'hello\xa9&welcome<br />&')
def test_unquote(self):
- self.assertEqual(adaptors.Unquote(keep=['amp', 'lt'])([u'hello&copy;&amp;welcome', u'&lt;br /&gt;&amp;']), [u'hello\xa9&amp;welcome', u'&lt;br />&amp;'])
-
+ unquote = adaptors.Unquote(keep=['amp', 'lt'])
+ self.assertEqual(unquote(u'hello&copy;&amp;welcome&lt;br /&gt;&amp;', {}),
+ u'hello\xa9&amp;welcome&lt;br />&amp;')
def test_remove_tags(self):
- test_data = ['<a href="lala">adsaas<br /></a>', '<div id="1"><table>dsadasf</table></div>']
- self.assertEqual(adaptors.remove_tags(test_data), ['adsaas', 'dsadasf'])
-
+ self.assertEqual(adaptors.remove_tags('<a href="lala">adsaas<br /></a>'), 'adsaas')
+ self.assertEqual(adaptors.remove_tags('<div id="1"><table>dsadasf</table></div>'), 'dsadasf')
def test_remove_root(self):
- self.assertEqual(adaptors.remove_root(['<div>lallaa<a href="coso">dsfsdfds</a>pepepep<br /></div>']),
- ['lallaa<a href="coso">dsfsdfds</a>pepepep<br />'])
-
+ self.assertEqual(adaptors.remove_root('<div>lallaa<a href="coso">dsfsdfds</a>pepepep<br /></div>'),
+ 'lallaa<a href="coso">dsfsdfds</a>pepepep<br />')
def test_remove_multispaces(self):
- self.assertEqual(adaptors.clean_spaces([' hello, whats up?', 'testing testingtesting testing']),
- [' hello, whats up?', 'testing testingtesting testing'])
-
+ self.assertEqual(adaptors.clean_spaces(' hello, whats up?'), ' hello, whats up?')
def test_strip(self):
- self.assertEqual(adaptors.strip([' hi there, sweety ;D ', ' I CAN HAZ TEST?? ']),
- ['hi there, sweety ;D', 'I CAN HAZ TEST??'])
self.assertEqual(adaptors.strip(' hello there, this is my test '),
- 'hello there, this is my test')
-
+ 'hello there, this is my test')
def test_drop_empty_elements(self):
self.assertEqual(adaptors.drop_empty([1, 2, None, 5, 0, 6, False, 'hi']),
- [1, 2, 5, 6, 'hi'])
-
+ [1, 2, 5, 6, 'hi'])
def test_delist(self):
- self.assertEqual(adaptors.Delist()(['hi', 'there', 'fellas.', 'this', 'is', 'my', 'test.']),
- 'hi there fellas. this is my test.')
+ delist = adaptors.Delist(' ')
+ self.assertEqual(delist(['hi', 'there', 'fellas.', 'this', 'is', 'my', 'test.'], {}),
+ 'hi there fellas. this is my test.')
+ self.assertEqual(delist(['hi', 'there', 'fellas,', 'this', 'is', 'my', 'test.'], {'join_delimiter': '.'}),
+ 'hi.there.fellas,.this.is.my.test.')
diff --git a/scrapy/trunk/scrapy/tests/test_robustscrapeditem.py b/scrapy/trunk/scrapy/tests/test_robustscrapeditem.py
new file mode 100644
index 000000000..34277dbd7
--- /dev/null
+++ b/scrapy/trunk/scrapy/tests/test_robustscrapeditem.py
@@ -0,0 +1,94 @@
+# -*- coding: utf8 -*-
+import unittest
+
+from scrapy.contrib.item import RobustScrapedItem
+from scrapy.item.adaptors import AdaptorPipe, AdaptorFunc
+from scrapy.contrib_exp import adaptors
+from scrapy.core.exceptions import UsageError
+
+class MyItem(RobustScrapedItem):
+ ATTRIBUTES = {
+ 'guid': basestring,
+ 'name': basestring,
+ 'children': [basestring],
+ 'age': int,
+ 'alive': bool,
+ }
+
+class RobustScrapedItemTestCase(unittest.TestCase):
+ def setUp(self):
+ self.item = MyItem()
+
+ def test_attribute_basic(self):
+ self.assertRaises(UsageError, self.item.attribute, 'foo')
+ self.assertRaises(AttributeError, self.item.attribute, 'foo', 'something')
+
+ self.item.attribute('name', 'John')
+ self.assertEqual(self.item.name, 'John')
+
+ self.assertRaises(TypeError, self.item.attribute, 'children', ['Peter'])
+ self.item.attribute('children', *['Peter'])
+ self.assertEqual(self.item.children, ['Peter'])
+
+ self.item.attribute('age', 40)
+ self.assertEqual(self.item.age, 40)
+
+ self.item.attribute('alive', False)
+ self.assertEqual(self.item.alive, False)
+
+ def test_attribute_override(self):
+ self.item.attribute('name', 'John')
+ self.item.attribute('name', 'Charlie')
+ self.assertEqual(self.item.name, 'John')
+
+ self.item.attribute('name', 'Charlie', override=True)
+ self.assertEqual(self.item.name, 'Charlie')
+
+ def test_attribute_add(self):
+ self.item.attribute('name', 'John')
+
+ self.item.attribute('name', 'Doe', add=True)
+ self.assertEqual(self.item.name, 'JohnDoe')
+
+ self.item.attribute('children', *['Ken', 'Tom'])
+ self.item.attribute('children', 'Bobby')
+ self.item.attribute('children', 'Jimmy', add=True)
+ self.assertEqual(self.item.children, ['Ken', 'Tom', 'Jimmy'])
+
+ self.item.attribute('children', *['Johnny', 'Rodrigo'], add=True)
+ self.assertEqual(self.item.children, ['Ken', 'Tom', 'Jimmy', 'Johnny', 'Rodrigo'])
+
+ def test_set_adaptors(self):
+ self.assertEqual(self.item._adaptors_dict, {})
+
+ delist = adaptors.Delist()
+ self.item.set_adaptors({'name': [adaptors.extract, delist]})
+ self.assertTrue(isinstance(self.item._adaptors_dict['name'], AdaptorPipe))
+ self.assertEqual(self.item._adaptors_dict['name'][0].name, "extract")
+ self.assertEqual(self.item._adaptors_dict['name'][1].name, "Delist")
+
+ self.item.set_adaptors({'description': [adaptors.extract]})
+ self.assertEqual(self.item._adaptors_dict['description'][0].name, "extract")
+
+ def test_set_attrib_adaptors(self):
+ self.assertEqual(self.item._adaptors_dict, {})
+
+ self.item.set_attrib_adaptors('name', [adaptors.extract, adaptors.strip])
+ self.assertTrue(isinstance(self.item._adaptors_dict['name'], AdaptorPipe))
+ self.assertEqual(self.item._adaptors_dict['name'][0].name, "extract")
+ self.assertEqual(self.item._adaptors_dict['name'][1].name, "strip")
+
+ unquote = adaptors.Unquote()
+ self.item.set_attrib_adaptors('name', [adaptors.extract, unquote])
+ self.assertTrue(isinstance(self.item._adaptors_dict['name'], AdaptorPipe))
+ self.assertEqual(self.item._adaptors_dict['name'][0].name, "extract")
+ self.assertEqual(self.item._adaptors_dict['name'][1].name, "Unquote")
+
+ def test_add_adaptor(self):
+ self.assertEqual(self.item._adaptors_dict, {})
+
+ self.item.add_adaptor('name', adaptors.strip)
+ self.assertEqual(self.item._adaptors_dict['name'][0].name, "strip")
+ self.item.add_adaptor('name', adaptors.extract, position=0)
+ self.assertEqual(self.item._adaptors_dict['name'][0].name, "extract")
+ self.assertEqual(self.item._adaptors_dict['name'][1].name, "strip")
diff --git a/scrapy/trunk/scrapy/tests/test_scrapeditem.py b/scrapy/trunk/scrapy/tests/test_scrapeditem.py
deleted file mode 100644
index a644d10da..000000000
--- a/scrapy/trunk/scrapy/tests/test_scrapeditem.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# -*- coding: utf8 -*-
-import unittest
-
-from scrapy.item.models import ScrapedItem
-from scrapy.item.adaptors import AdaptorPipe
-from scrapy.contrib import adaptors
-
-class ScrapedItemTestCase(unittest.TestCase):
- def setUp(self):
- self.item = ScrapedItem()
-
- def test_attribute_basic(self):
- self.item.attribute('name', 'John')
- self.assertEqual(self.item.name, 'John')
-
- def test_attribute_override(self):
- self.item.attribute('name', 'John')
- self.item.attribute('name', 'Charlie')
- self.assertEqual(self.item.name, 'John')
-
- self.item.attribute('name', 'Charlie', override=True)
- self.assertEqual(self.item.name, 'Charlie')
-
- def test_attribute_add(self):
- self.item.attribute('name', 'John')
-
- self.item.attribute('name', 'Doe', add=True)
- self.assertEqual(self.item.name, 'JohnDoe')
-
- self.item.attribute('name', 'Smith', add=' ')
- self.assertEqual(self.item.name, 'JohnDoe Smith')
-
- self.item.attribute('children', ['Ken', 'Tom'])
- self.item.attribute('children', 'Bobby')
- self.item.attribute('children', 'Jimmy', add=True)
- self.assertEqual(self.item.children, ['Ken', 'Tom', 'Jimmy'])
-
- self.item.attribute('children', ['Johnny', 'Rodrigo'], add=True)
- self.assertEqual(self.item.children, ['Ken', 'Tom', 'Jimmy', 'Johnny', 'Rodrigo'])
-
- def test_set_adaptors(self):
- self.assertEqual(self.item._adaptors_dict, {})
-
- delist = adaptors.Delist()
- self.item.set_adaptors({'name': [adaptors.extract, delist]})
- self.assertEqual(self.item._adaptors_dict, {'name': [adaptors.extract, delist]})
-
- self.item.set_adaptors({'description': [adaptors.extract]})
- self.assertEqual(self.item._adaptors_dict, {'description': [adaptors.extract]})
-
- def test_set_attrib_adaptors(self):
- self.assertEqual(self.item._adaptors_dict, {})
-
- self.item.set_attrib_adaptors('name', [adaptors.extract, adaptors.strip])
- self.assertEqual(self.item._adaptors_dict['name'],
- AdaptorPipe([adaptors.extract, adaptors.strip]))
-
- unquote = adaptors.Unquote()
- self.item.set_attrib_adaptors('name', [adaptors.extract, unquote])
- self.assertEqual(self.item._adaptors_dict['name'],
- AdaptorPipe([adaptors.extract, unquote]))
-
- def test_add_adaptor(self):
- self.assertEqual(self.item._adaptors_dict, {})
-
- self.item.add_adaptor('name', adaptors.strip)
- self.assertEqual(self.item._adaptors_dict['name'], [adaptors.strip])
- self.item.add_adaptor('name', adaptors.extract, position=0)
- self.assertEqual(self.item._adaptors_dict['name'], [adaptors.extract, adaptors.strip])
-
diff --git a/scrapy/trunk/scrapy/tests/test_utils_misc.py b/scrapy/trunk/scrapy/tests/test_utils_misc.py
index 1f6430d9b..ecf3858ce 100644
--- a/scrapy/trunk/scrapy/tests/test_utils_misc.py
+++ b/scrapy/trunk/scrapy/tests/test_utils_misc.py
@@ -14,19 +14,19 @@ class UtilsMiscTestCase(unittest.TestCase):
def test_items_to_csv(self):
item_1 = ScrapedItem()
- item_1.attribute('_hidden', '543565')
- item_1.attribute('id', '3213')
- item_1.attribute('name', 'Item 1')
- item_1.attribute('description', 'Really cute item')
- item_1.attribute('url', 'http://dummyurl.com')
+ item_1._hidden = '543565'
+ item_1.id = '3213'
+ item_1.name = 'Item 1'
+ item_1.description = 'Really cute item'
+ item_1.url = 'http://dummyurl.com'
item_2 = ScrapedItem()
- item_2.attribute('_hidden', 'lala')
- item_2.attribute('id', '1234')
- item_2.attribute('name', 'Item 2')
- item_2.attribute('description', 'This item rocks!')
- item_2.attribute('url', 'http://dummyurl.com/2')
- item_2.attribute('supplier', 'A random supplier')
+ item_2._hidden = 'lala'
+ item_2.id = '1234'
+ item_2.name = 'Item 2'
+ item_2.description = 'This item rocks!'
+ item_2.url = 'http://dummyurl.com/2'
+ item_2.supplier = 'A random supplier'
file = StringIO()
items_to_csv(file, [item_1, item_2])