Skip to content

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

Replace `contenttype` references by `type`

Daniel Graña14613638099d
diff --git a/docs/topics/selectors.rst b/docs/topics/selectors.rst
index fd986d0cd..efc61a100 100644
--- a/docs/topics/selectors.rst
+++ b/docs/topics/selectors.rst
@@ -249,18 +249,34 @@ Built-in Selectors reference
.. module:: scrapy.selector
:synopsis: Selector class
-.. class:: Selector(response, contenttype=None)
+.. class:: Selector(response=None, text=None, type=None)
- An instance of :class:`Selector` is a wrapper over ``response`` to select
+ An instance of :class:`Selector` is a wrapper over response to select
certain parts of its content.
``response`` is a :class:`~scrapy.http.HtmlResponse` or
:class:`~scrapy.http.XmlResponse` object that will be used for selecting and
extracting data.
- ``contenttype`` tells what parser and selection flavor is used to parse the
- response body. It defaults to ``"html"`` for :class:`~scrapy.http.HtmlResponse`
- and ``"xml"`` for :class:`~scrapy.http.XmlResponse`.
+ ``text`` is a unicode string or utf-8 encoded text for cases when a
+ ``response`` isn't available. Using ``text`` and ``response`` together is
+ undefined behavior.
+
+ ``type`` defines the selector type, it can be ``"html"``, ``"xml"`` or ``None`` (default).
+
+ If ``type`` is ``None``, the selector automatically chooses the best type
+ based on ``response`` type (see below), or defaults to ``"html"`` in case it
+ is used together with ``text``.
+
+ If ``type`` is ``None`` and a ``response`` is passed, the selector type is
+ inferred from the response type as follow:
+
+ * ``"html"`` for :class:`~scrapy.http.HtmlResponse` type
+ * ``"xml"`` for :class:`~scrapy.http.XmlResponse` type
+ * ``"html"`` for anything else
+
+ Otherwise, if ``type`` is set, the selector type will be forced and no
+ detection will occur.
.. method:: xpath(query)
diff --git a/scrapy/contrib/spiders/feed.py b/scrapy/contrib/spiders/feed.py
index 6d8e0a358..271b3a97a 100644
--- a/scrapy/contrib/spiders/feed.py
+++ b/scrapy/contrib/spiders/feed.py
@@ -71,11 +71,11 @@ class XMLFeedSpider(BaseSpider):
if self.iterator == 'iternodes':
nodes = self._iternodes(response)
elif self.iterator == 'xml':
- selector = Selector(response, contenttype='xml')
+ selector = Selector(response, type='xml')
self._register_namespaces(selector)
nodes = selector.xpath('//%s' % self.itertag)
elif self.iterator == 'html':
- selector = Selector(response, contenttype='html')
+ selector = Selector(response, type='html')
self._register_namespaces(selector)
nodes = selector.xpath('//%s' % self.itertag)
else:
diff --git a/scrapy/contrib_exp/iterators.py b/scrapy/contrib_exp/iterators.py
index ecc6265d0..7cf9103fd 100644
--- a/scrapy/contrib_exp/iterators.py
+++ b/scrapy/contrib_exp/iterators.py
@@ -11,7 +11,7 @@ def xmliter_lxml(obj, nodename, namespace=None):
for _, node in iterable:
nodetext = etree.tostring(node)
node.clear()
- xs = Selector(text=nodetext, contenttype='xml')
+ xs = Selector(text=nodetext, type='xml')
if namespace:
xs.register_namespace('x', namespace)
yield xs.xpath(selxpath)[0]
diff --git a/scrapy/selector/lxmlsel.py b/scrapy/selector/lxmlsel.py
index bc655b523..de897d2fd 100644
--- a/scrapy/selector/lxmlsel.py
+++ b/scrapy/selector/lxmlsel.py
@@ -10,7 +10,7 @@ __all__ = ['HtmlXPathSelector', 'XmlXPathSelector', 'XPathSelector',
class XPathSelector(Selector):
__slots__ = ()
- default_contenttype = 'html'
+ _default_type = 'html'
def __init__(self, *a, **kw):
import warnings
@@ -28,12 +28,12 @@ class XPathSelector(Selector):
class XmlXPathSelector(XPathSelector):
__slots__ = ()
- default_contenttype = 'xml'
+ _default_type = 'xml'
class HtmlXPathSelector(XPathSelector):
__slots__ = ()
- default_contenttype = 'html'
+ _default_type = 'html'
class XPathSelectorList(SelectorList):
diff --git a/scrapy/selector/unified.py b/scrapy/selector/unified.py
index 77cd9e11f..a316c20cf 100644
--- a/scrapy/selector/unified.py
+++ b/scrapy/selector/unified.py
@@ -25,38 +25,37 @@ _ctgroup = {
}
-def _ct(response, ct):
- if ct is None:
+def _st(response, st):
+ if st is None:
return 'xml' if isinstance(response, XmlResponse) else 'html'
- elif ct in ('xml', 'html'):
- return ct
+ elif st in ('xml', 'html'):
+ return st
else:
- raise ValueError('Invalid contenttype: %s' % ct)
+ raise ValueError('Invalid type: %s' % st)
-def _response_from_text(text, ct):
- rt = XmlResponse if ct == 'xml' else HtmlResponse
+def _response_from_text(text, st):
+ rt = XmlResponse if st == 'xml' else HtmlResponse
return rt(url='about:blank', encoding='utf-8',
body=unicode_to_str(text, 'utf-8'))
class Selector(object_ref):
- __slots__ = ['response', 'text', 'namespaces', 'contenttype', '_expr', '_root',
+ __slots__ = ['response', 'text', 'namespaces', 'type', '_expr', '_root',
'__weakref__', '_parser', '_csstranslator', '_tostring_method']
- default_contenttype = None
+ _default_type = None
- def __init__(self, response=None, text=None, namespaces=None, contenttype=None,
+ def __init__(self, response=None, text=None, type=None, namespaces=None,
_root=None, _expr=None):
-
- self.contenttype = ct = _ct(response, contenttype or self.default_contenttype)
- self._parser = _ctgroup[ct]['_parser']
- self._csstranslator = _ctgroup[ct]['_csstranslator']
- self._tostring_method = _ctgroup[ct]['_tostring_method']
+ self.type = st = _st(response, type or self._default_type)
+ self._parser = _ctgroup[st]['_parser']
+ self._csstranslator = _ctgroup[st]['_csstranslator']
+ self._tostring_method = _ctgroup[st]['_tostring_method']
if text is not None:
- response = _response_from_text(text, ct)
+ response = _response_from_text(text, st)
if response is not None:
_root = LxmlDocument(response, self._parser)
@@ -82,7 +81,7 @@ class Selector(object_ref):
result = [self.__class__(_root=x, _expr=query,
namespaces=self.namespaces,
- contenttype=self.contenttype)
+ type=self.type)
for x in result]
return SelectorList(result)
@@ -169,4 +168,3 @@ class SelectorList(list):
@deprecated(use_instead='.xpath()')
def select(self, xpath):
return self.xpath(xpath)
-
diff --git a/scrapy/tests/test_selector.py b/scrapy/tests/test_selector.py
index d8ff6d346..93d0b9532 100644
--- a/scrapy/tests/test_selector.py
+++ b/scrapy/tests/test_selector.py
@@ -59,23 +59,23 @@ class SelectorTestCase(unittest.TestCase):
"""Test that XML and HTML Selector's behave differently"""
# some text which is parsed differently by XML and HTML flavors
text = '<div><img src="a.jpg"><p>Hello</div>'
- hs = self.sscls(text=text, contenttype='html')
+ hs = self.sscls(text=text, type='html')
self.assertEqual(hs.xpath("//div").extract(),
[u'<div><img src="a.jpg"><p>Hello</p></div>'])
- xs = self.sscls(text=text, contenttype='xml')
+ xs = self.sscls(text=text, type='xml')
self.assertEqual(xs.xpath("//div").extract(),
[u'<div><img src="a.jpg"><p>Hello</p></img></div>'])
def test_flavor_detection(self):
text = '<div><img src="a.jpg"><p>Hello</div>'
sel = self.sscls(XmlResponse('http://example.com', body=text))
- self.assertEqual(sel.contenttype, 'xml')
+ self.assertEqual(sel.type, 'xml')
self.assertEqual(sel.xpath("//div").extract(),
[u'<div><img src="a.jpg"><p>Hello</p></img></div>'])
sel = self.sscls(HtmlResponse('http://example.com', body=text))
- self.assertEqual(sel.contenttype, 'html')
+ self.assertEqual(sel.type, 'html')
self.assertEqual(sel.xpath("//div").extract(),
[u'<div><img src="a.jpg"><p>Hello</p></div>'])
@@ -183,7 +183,7 @@ class SelectorTestCase(unittest.TestCase):
def test_selector_over_text(self):
hs = self.sscls(text='<root>lala</root>')
self.assertEqual(hs.extract(), u'<html><body><root>lala</root></body></html>')
- xs = self.sscls(text='<root>lala</root>', contenttype='xml')
+ xs = self.sscls(text='<root>lala</root>', type='xml')
self.assertEqual(xs.extract(), u'<root>lala</root>')
self.assertEqual(xs.xpath('.').extract(), [u'<root>lala</root>'])
diff --git a/scrapy/utils/iterators.py b/scrapy/utils/iterators.py
index 67f9946e6..18fa56de4 100644
--- a/scrapy/utils/iterators.py
+++ b/scrapy/utils/iterators.py
@@ -29,7 +29,7 @@ def xmliter(obj, nodename):
r = re.compile(r"<%s[\s>].*?</%s>" % (nodename, nodename), re.DOTALL)
for match in r.finditer(text):
nodetext = header_start + match.group() + header_end
- yield Selector(text=nodetext, contenttype='xml').xpath('//' + nodename)[0]
+ yield Selector(text=nodetext, type='xml').xpath('//' + nodename)[0]
def csviter(obj, delimiter=None, headers=None, encoding=None):