2

I need to check scraped fields which contain non-ascii characters. When I include a utf-8 literal in the spider, I get this error:

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

Here is an example that produces the error

# -*- coding: utf-8 -*-
import scrapy

class DummySpider(scrapy.Spider):
    name = 'dummy'
    start_urls = ['http://www.google.com']

    def parse(self, response):
        dummy = response.xpath("//*[contains(.,u'café')]")

This is the traceback:

Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 577, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/tmp/stack.py", line 9, in parse
    dummy = response.xpath("//*[contains(.,u'café')]")
  File "/usr/lib/pymodules/python2.7/scrapy/http/response/text.py", line 109, in xpath
    return self.selector.xpath(query)
  File "/usr/lib/pymodules/python2.7/scrapy/selector/unified.py", line 97, in xpath
    smart_strings=self._lxml_smart_strings)
  File "lxml.etree.pyx", line 1509, in lxml.etree._Element.xpath (src/lxml/lxml.etree.c:50702)
  File "xpath.pxi", line 306, in lxml.etree.XPathElementEvaluator.__call__ (src/lxml/lxml.etree.c:145829)
  File "apihelpers.pxi", line 1395, in lxml.etree._utf8 (src/lxml/lxml.etree.c:26485)
ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters
user3185563
  • 1,314
  • 2
  • 15
  • 22

1 Answers1

7
"//*[contains(.,u'café')]"

u'' string literals are Python syntax, not part of XPath. Try:

u"//*[contains(.,'café')]"
bobince
  • 528,062
  • 107
  • 651
  • 834