2017-09-05 81 views
0

由於某些原因,當我使用Scrapy從元素中獲取文本值時,它顯示正確,但是當我將它放入數組中時,它會被不正確地編碼。Scrapy編碼數據錯誤

這裏是測試:我用了Château這個詞。在一個案例測試,scrapy獲取單詞然後打印並將其添加到數組。在第二種情況下test2,我從字面上將從另一個測試打印的單詞粘貼到數組中。

這裏是我的Scrapy python腳本:

value=node.xpath('//AddrDisplayMemberSerialization/text()').extract_first() 
print value; 
array={'test':value,'test2':'Château'} 
print array 

自動,數組編碼值。 Python會自動執行此操作還是Scrapy執行此操作?

enter image description here

他們爲什麼得到編碼不同?

+1

是的。 Python自動完成它。在Python3中,Unicode字符串看起來是正確的 – AndMar

+0

@marni所以在Python 3中它將全部正確嗎? –

+1

是的。但在Py2中它也是正確的(簡而言之:只是視圖不同而已,long:Python 2和3以不同的方式使用Unicode),請不要擔心 – AndMar

回答

1

問題是因爲Python2和Python3之間的差異。如果你這樣做在Python3它的工作馬上

Python 3.6.2 (default, Jul 17 2017, 16:44:45) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> value = 'Château' 
>>> print (value) 
Château 
>>> array={'test':value,'test2':'Château'} 
>>> print(array) 
{'test': 'Château', 'test2': 'Château'} 
>>> 

現在讓我們回到Python2

Python 2.7.13 (default, Jul 18 2017, 09:17:00) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> value = 'Château' 
>>> print value; 
Château 
>>> array={'test':value,'test2':'Château'} 
>>> print array 
{'test': 'Ch\xc3\xa2teau', 'test2': 'Ch\xc3\xa2teau'} 

這是因爲當您打印陣列,它被轉換爲字符串表示和蟒蛇不是Unicode

>>> str(array) 
"{'test': 'Ch\\xc3\\xa2teau', 'test2': 'Ch\\xc3\\xa2teau'}" 
>>> print str(array) 
{'test': 'Ch\xc3\xa2teau', 'test2': 'Ch\xc3\xa2teau'} 

你想要做什麼,而印刷是做Unicode轉義

>>> print str(array).decode("unicode-escape") 
{'test': 'Château', 'test2': 'Château'} 

但等待這樣弄亂打印?這是因爲需要打印這些字符的編碼。拉丁語短片

>>> print str(array).decode("unicode-escape").encode("latin-1") 
{'test': 'Château', 'test2': 'Château'} 

只需升級到python3,您的問題將被排序。但是您需要將打印報表更改爲print(...)。否則使用代碼來編碼編碼,如我所示

1

這就是它將如何顯示在終端。

但如果你想讓它在UTF-8只顯示這樣做是settings.py

FEED_EXPORT_ENCODING = 'utf-8' 
+0

我試過了,它沒有工作。 –

+0

@MaciekSemik正如我告訴你,數據將不會在終端顯示爲UTF-8,但如果你做'scrapy抓取spider_name -o output.json',你將得到正確的編碼 – Umair

+0

我有# - * - 編碼:utf-8 - * - –