2013-12-21 17 views
0

我想抓取一個站點118.69.35.146/sjc/來測試SCRAPY框架。我用HTMLXPathSelector選擇,詳情如下任務的代碼片段:如何在Scrapy中使用HtmlXpathSelector在​​</td>之間獲取數據?

def parse(self, response): 
    sel = HtmlXPathSelector(response) 
    sites = sel.select('//table[@id="grv_GiaVangUpdate"]/tr') 
    items = [] 
    for site in sites: 
     item = FinanceItem() 
     item['buy'] = site.select('//td[3]/text()').extract() 
     item['sell'] = site.select('//td[4]/text()').extract() 
     items.append(item) 
    return items 

我希望得到的文本數據值和。

但是JSON文件輸出的結果我剛剛得到了總共16個節點的空值。

[{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}, 
{"sell": [], "buy": []}] 

請問這裏的任何專家爲我檢查這段代碼,教我哪一點我錯了。

在此先感謝!

回答

1

查看頁面的源代碼並在Firepath中測試查詢,我發現它應該可以工作。

驗證你實際上得到相同的頁面:把pdb/ipdb斷點(import ipdb; ipdb.set_trace()sel = HtmlXPathSelector(response)後,看看裏面有什麼response。然後逐步調試您的程序以查看失敗的原因和原因。

0

您應該始終使用scrapy shell(scrapy shell 'http://118.69.35.146/sjc/')ant不僅與其他工具一起測試xpath。

對於這個網站,對於相同的元素,firefox有類似<td align="center">34,870</td>而scrapy有<td align="center"><font face="Times New Roman" color="Black" size="3">34,870</font></td>。所以你想要'//td[3]/font/text()'或者更好的'//td[3]//text()'

但你會得到其他問題......當你做site.select('//td[3]/text()').extract(),你正在搜索所有的樹,而不僅僅是'//table[@id="grv_GiaVangUpdate"]/tr',因爲我想,你想要的。您應該使用'.//td[3]/text()',並在開始時指出一點。

注意:select已棄用,請改爲使用xpath()。

相關問題