2016-02-09 32 views
14

我試圖用scrapy蜘蛛去除\ r \ n \ t字符,然後生成一個json文件。scrapy中的Strip n t r

我有一個充滿新行的「描述」對象,它不會做我想要的:將每個描述與標題匹配。

我試着用map(unicode.strip()),但它並沒有真正起作用。作爲scrapy的新手,我不知道是否有另一種更簡單的方法或map unicode的真實工作方式。

這是我的代碼:

def parse(self, response): 
    for sel in response.xpath('//div[@class="d-grid-main"]'): 
     item = xItem() 
     item['TITLE'] = sel.xpath('xpath').extract() 
     item['DESCRIPTION'] = map(unicode.strip, sel.xpath('//p[@class="class-name"]/text()').extract()) 

我也試過:

item['DESCRIPTION'] = str(sel.xpath('//p[@class="class-name"]/text()').extract()).strip() 

但它引發的錯誤。最好的方法是什麼?

+0

你好,你說的「它並沒有真正的工作」是什麼意思? 'strip()'只考慮前導字符和尾隨字符,所以如果你想去掉字符串中的任何東西,你需要其他方法。 'import re'和're.sub('[\ r \ n \ t]','','Hel \ nlo \ r!')'可以幫助解決這個問題。 –

+0

我會建議結帳'ItemLoader's http://doc.scrapy.org/en/latest/topics/loaders.html它允許你管理輸入和輸出你的'Item's – Granitosaurus

+0

QuentinPradet謝謝,實際上是保羅的答案很好,我不知道。和Granitosaurus我會學習,謝謝 –

回答

13

unicode.strip只涉及開頭空格字符和字符串

返回去除了開頭和結尾字符的字符串的副本結束。

\n\r,或\t在中間。

你可以使用一個自定義的方法,以除去該字符串內的那些字符(使用正則表達式模塊),或者甚至使用XPath's normalize-space()

返回參數串與空白通過汽提的前緣和後空白歸一化並用單個空格替換空白字符序列

例蟒蛇shell會話:

>>> text='''<html> 
... <body> 
... <div class="d-grid-main"> 
... <p class="class-name"> 
... 
... This is some text, 
... with some newlines \r 
... and some \t tabs \t too; 
... 
... <a href="http://example.com"> and a link too 
... </a> 
... 
... I think we're done here 
... 
... </p> 
... </div> 
... </body> 
... </html>''' 
>>> response = scrapy.Selector(text=text) 
>>> response.xpath('//div[@class="d-grid-main"]') 
[<Selector xpath='//div[@class="d-grid-main"]' data=u'<div class="d-grid-main">\n<p class="clas'>] 
>>> div = response.xpath('//div[@class="d-grid-main"]')[0] 
>>> 
>>> # you'll want to use relative XPath expressions, starting with "./" 
>>> div.xpath('.//p[@class="class-name"]/text()').extract() 
[u'\n\n This is some text,\n with some newlines \r\n and some \t tabs \t too;\n\n', 
u"\n\nI think we're done here\n\n"] 
>>> 
>>> # only leading and trailing whitespace is removed by strip() 
>>> map(unicode.strip, div.xpath('.//p[@class="class-name"]/text()').extract()) 
[u'This is some text,\n with some newlines \r\n and some \t tabs \t too;', u"I think we're done here"] 
>>> 
>>> # normalize-space() will get you a single string on the whole element 
>>> div.xpath('normalize-space(.//p[@class="class-name"])').extract() 
[u"This is some text, with some newlines and some tabs too; and a link too I think we're done here"] 
>>> 
+0

我想正常化空間整體: response.xpath('。')。extract() 這可以工作,但使用規範化空間: response.xpath('normalize-space (。)')。extract() 像這樣的html標籤被刪除了,爲什麼? – Baks

+0

@Baks,['normalize-space(。)'](https://www.w3.org/TR/xpath/#function-normalize-space)返回空間標準化的[字符串值](https:// www.w3.org/TR/xpath/#element-nodes),它是後代文本節點的連接:_「元素節點的字符串值是所有文本的字符串值的連接元素節點的節點後代按文檔順序排列。「_ –

4

保羅trmbrth表明in his answer

div.xpath('normalize-space(.//p[@class="class-name"])').extract() 

很可能是你想要的。但是,normalize-space也會將字符串中包含的空白字符壓縮到一個空格中。如果只想刪除\r\n\t而不打擾其他空格,則可以使用translate()刪除字符。

trans_table = {ord(c): None for c in u'\r\n\t'} 
item['DESCRIPTION] = ' '.join(s.translate(trans_table) for s in sel.xpath('//p[@class="class-name"]/text()').extract()) 

這仍然會留下開頭和結尾的空白,是不是在設定\r\n,或\t。如果你也想擺脫的只是插入一個呼叫strip()

item['DESCRIPTION] = ' '.join(s.strip().translate(trans_table) for s in sel.xpath('//p[@class="class-name"]/text()').extract()) 
+0

完美。我從來不知道這一點,它解決了所有我沒有正則表達式的空白問題。 – Echelon

+0

div.xpath('normalize-space(.// p [@ class =「class-name」])')。extract() 爲我工作,謝謝。 –

3

我是蟒蛇,scrapy新手,我也曾有過類似的問題的今天,解決了這個具有以下模塊的幫助/ function w3lib.html.replace_escape_chars我已經爲我的物品加載器創建了一個默認輸入處理器,並且它沒有任何問題,您可以將其綁定到特定的scrapy上。現場(也),以及它與CSS選擇器和CSV飼料出口的好東西:

from w3lib.html import replace_escape_chars 
yourloader.default_input_processor = MapCompose(relace_escape_chars) 
相關問題