2014-02-18 128 views
1

我試圖讓一個Scrapy蜘蛛抓取一個網站,但我需要的物品中的一個元素是用西班牙語寫的,使用帶有波浪號的元音(í )。scrapy選擇器字符串不接受國際字符

TITULO = title.select(U '.// [ 「TITULO原文:」] /文()' 提取物()

我發現這裏類似的問題,但接受了他們的答案沒」。我將不起作用。

添加的U在字符串的開始注意到一些問題護理,但給我的錯誤

UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 21: ordinal not in range(128) 

我發現這裏的其他問題建議使用」 ... /文(')解碼('utf-8),但這樣做或使用.encode('utf-8'),而不是給我錯誤

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

是否有東西我失蹤或其他方式或我更好的製作一個正則表達式來捕獲我的字符串的其他部分,但那封信?

下面的代碼我到目前爲止:

def parse(self, response): 
    #change the response to an HtmlResponse to allow for utf-8 encoding of the body. 
response = HtmlResponse(url=response.url, status=response.status, headers=response.headers, body=response.body) 

print '\n\nresponse encoding', response.encoding ##the page is encoded in utf-8 

hxs = HtmlXPathSelector(response) 
    titles = hxs.select('//div[@class="datosespectaculo"]') 

    items = [] 
    for title in titles:   
     item = CarteleraItem() 
     titulo=title.select(u'.//["Título Original:"]/text()'.encode('utf-8')).extract() 
     Ano=title.select('.//span[@itemprop="copyrightYear"]/text').extract() 
     item ["title"] = titulo 
     item ["Ano"] = Ano 
     items.append(item) 

下面是對網頁的源以供參考

<div id="contgeneral"> 
<div class="contyrasca"> 
<div id="contfix"> 
<div class="contespectaculo"> 

<div class="colizq"><div itemscope itemtype="http://schema.org/Movie"> 
<h1 class="titulo" itemprop="name">15.361</h1> 

<img class="afiche" src="http://www.cartelera.com.uy/imagenes_espectaculos/musicdetail13/14770.jpg"/> 
<div class="datosespectaculo"> 

<strong>Título Original:</strong> <em>15.361</em><br /> 

<strong>Año: </strong><span itemprop="copyrightYear">2014</span><br /> 
<strong>Género: </strong><span itemprop="genre">Comedia/Drama</span><br /> 
<strong>Duración: </strong><span itemprop="duration">60&#39;</span><br /> 
<strong>Calificación: </strong>+18 años<br /> 

回答

0

嘗試添加下面一行到你的Python文件的開頭:

# -*- coding: utf-8 -*- 

有關完整說明,請參閱read the docs

+0

沒錯。請參閱http://docs.python.org/2/howto/unicode.html#unicode-literals-in-python-source-code –

+0

謝謝@pault。,添加了答案的鏈接。 – Tzach

+0

我已經嘗試過了(忘了說,抱歉),它沒有解決問題。 – ConnorU

1

如果# -*- coding: utf-8 -*-不起作用,您可以使用unicode字符串,其中非ASCII字符使用\u轉義序列。

所以你XPath的選擇變成了:

titulo=title.select(u'.//["T\u00edtulo Original:"]/text()'.encode('utf-8')).extract() 

我通常使用一個簡單的Python shell會話檢查轉義序列:

[email protected]:~$ python 
Python 2.7.3 (default, Jan 2 2013, 13:56:14) 
[GCC 4.7.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> u'.//["Título Original:"]/text()' 
u'.//["T\xedtulo Original:"]/text()' 
>>> u'.//["T\u00edtulo Original:"]/text()' 
u'.//["T\xedtulo Original:"]/text()' 
>>>