view raw - 10 months ago 61
Python Question

UnicodeEncodeError after setting restrict_xpaths settings

i'm new to python and scrapy. After setting restrict_xpaths settings to "//table[@class="lista"]" I've received following traceback. What's strange, by using other xpath rule the crawler works properly.

Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/", line 800, in runUntilCurrent
call.func(*call.args, **
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/", line 602, in _tick
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/", line 479, in _oneWorkUnit
result =
File "/Library/Python/2.7/site-packages/scrapy/utils/", line 57, in <genexpr>
work = (callable(elem, *args, **named) for elem in iterable)
--- <exception caught here> ---
File "/Library/Python/2.7/site-packages/scrapy/utils/", line 96, in iter_errback
File "/Library/Python/2.7/site-packages/scrapy/contrib/spidermiddleware/", line 23, in process_spider_output
for x in result:
File "/Library/Python/2.7/site-packages/scrapy/contrib/spidermiddleware/", line 22, in <genexpr>
return (_set_referer(r) for r in result or ())
File "/Library/Python/2.7/site-packages/scrapy/contrib/spidermiddleware/", line 33, in <genexpr>
return (r for r in result or () if _filter(r))
File "/Library/Python/2.7/site-packages/scrapy/contrib/spidermiddleware/", line 50, in <genexpr>
return (r for r in result or () if _filter(r))
File "/Library/Python/2.7/site-packages/scrapy/contrib/spiders/", line 73, in _parse_response
for request_or_item in self._requests_to_follow(response):
File "/Library/Python/2.7/site-packages/scrapy/contrib/spiders/", line 52, in _requests_to_follow
links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
File "/Library/Python/2.7/site-packages/scrapy/contrib/linkextractors/", line 124, in extract_links
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
exceptions.UnicodeEncodeError: 'charmap' codec can't encode character u'\xbb' in position 686: character maps to <undefined>

Here is MySpider Class.

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from ds_crawl.items import DsCrawlItem

class MySpider(CrawlSpider):
name = 'inside'
allowed_domains = ['']
start_urls = ['']

rules = (
Rule(SgmlLinkExtractor(allow=('show_stancja'), restrict_xpaths=('//table[@class="lista"]')), callback='parse_item', follow= True),)

def parse_item(self, response):
hxs = HtmlXPathSelector(response)
titles ="//p[@class='bbtext intextAd']")
for titles in titles:
item = DsCrawlItem()
item['content'] ="text()").extract()
print item

Any explanation of this error and help will be appreciated. Thank you.


That's a bug caused by the web page using the &raquo; entity which is translated by lxml to the unicode character \xbb and when you use the restrict_xpaths argument the link extractors encodes the content to the original encoding iso8859-2 which fails because \xbb is not valid character in that encoding.

This simple line reproduces the exception:

>>> u'\xbb'.encode('iso8859-2')
UnicodeEncodeError: 'charmap' codec can't encode character u'\xbb' in position 0: character maps to <undefined>

A workaround for this can be forcing to use utf8 for all responses. This can be done by a simple downloader middleware:

# file: myproject/

class ForceUTF8Response(object):
    """A downloader middleware to force UTF-8 encoding for all responses."""
    encoding = 'utf-8'

    def process_response(self, request, response, spider):
        # Note: Use response.body_as_unicode() instead of response.text in in Scrapy <1.0.
        new_body = response.text.encode(self.encoding)
        return response.replace(body=new_body, encoding=self.encoding)

In your settings:

    'myproject.middlewares.ForceUTF8Response': 100,