2016-12-17 55 views
0

我按照scrapy文檔中的「tutorial」提取了引用的標題。問題是,它在標題的開頭和結尾處給了我兩個unicode。Scrapy「Quotes Tutorial」 - 提取文本中的Unicode

>>>quote = response.css("div.quote")[0] 
>>> quote 
<Selector xpath=u"descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data=u'<div class="quote" itemscope itemtype="h'> 
>>> title = quote.css("span.text::text").extract_first() 
>>> title 
u'\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d' 
>>> 

在文檔中提取的標題是這樣的:

>>>title 
'"The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."' 
>>> 

我真的不知道我做錯了什麼在這裏,只是跟着的文檔。有沒有在配置文件中設置的東西,或者我該如何解決這個問題? 關於解碼/編碼unicode沒有提及。

其他實施例

我接着與scrapy文檔,這裏是一個例子:

Scrapy殼牌輸入:

>>> for quote in response.css("div.quote"): 
...  text = quote.css("span.text::text").extract_first() 
...  author = quote.css("small.author::text").extract_first() 
...  tags = quote.css("div.tags a.tag::text").extract() 
...  print(dict(text=text, author=author, tags=tags)) 

輸出段:

{'text': u'\u201cTry not to become a man of success. Rather become a man of value.\u201d', 'tags': [u'humor', u'obvious', u'simile'], 'author': u'Albert Einstein'} 
{'text': u'\u201cIt is better to be hated for what you are than to be loved for what you are not.\u201d', 'tags': [u'humor', u'obvious', u'simile'], 'author': u'Albert Einstein'} 
{'text': u"\u201cI have not failed. I've just found 10,000 ways that won't work.\u201d", 'tags': [u'humor', u'obvious', u'simile'], 'author': u'Albert Einstein'} 
{'text': u"\u201cA woman is like a tea bag; you never know how strong it is until it's in hot water.\u201d", 'tags': [u'humor', u'obvious', u'simile'], 'author': u'Albert Einstein'} 
{'text': u'\u201cA day without sunshine is like, you know, night.\u201d', 'tags': [u'humor', u'obvious', u'simile'], 'author': u'Albert Einstein'} 

網站我從:

[http://quotes.toscrape.com]

文檔Scrapy(第20頁):

https://media.readthedocs.org/pdf/scrapy/1.2/scrapy.pdf

系統:

MACOS達爾文內核版本16.3.0:星期四11月17日20時23分58秒PST 2016年根:XNU-3789.31.2〜1/RELEASE_X86_64

的virtualenv scrapy 的Python 2.7.10

更新

我試圖在同一用新的virtualenv的Python 3.5.2 使用Python 3.5。 2我終於得到了正確的結果,沒有像其他設置中的unicode問題。

回答

1

您所看到的是字符串的調試表示形式,因爲您只是在解釋器中查看變量而不是打印它。在Python 2.7中,所有不可打印的非ASCII字符都使用轉義碼顯示。在Python 3中,只有當前終端編碼中可顯示的字符會顯示爲轉義碼。

打印字符串以強制顯示字符。

>>> s=u'\u201cThe world\u201d' 
>>> s 
u'\u201cThe world\u201d' 
>>> print s 
「The world」 

可以得到UnicodeEncodeError如果打印終端使用不支持非ASCII字符的編碼,但因爲Python 3.5爲你的作品,你的終端必須支持他們。

請注意,調試顯示屏還顯示代表Unicode字符串的u並引用輸出。 print只是顯示字符串內容。

+0

謝謝您的回答;) – Luca