簡體   English   中英

Python:Scrapy CSV導出錯誤?

[英]Python: Scrapy CSV exports incorrectly?

我只是想寫一個csv。 但是,我有兩個單獨的For-Statement,因此每個For-Statement的數據都獨立導出並中斷順序。 建議?

def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select('//td[@class="title"]')
        subtext = hxs.select('//td[@class="subtext"]')
        items = []
        for title in titles:
            item = HackernewsItem()
            item["title"] = title.select("a/text()").extract()
            item["url"] = title.select("a/@href").extract()
            items.append(item)
        for score in subtext:
            item = HackernewsItem()
            item["score"] = score.select("span/text()").extract()
            items.append(item)
        return items

從下圖中可以明顯看出,第二個for語句在標題下打印,而不是在標題中“打印”。

附上CSV圖片: CSV文件

和完整文件的github鏈接: https//github.com/nchlswtsn/scrapy/blob/master/items.csv

您導出元素的順序與在CSV文件中找到的邏輯順序一致,首先導出所有標題,然后導出所有子文本元素。
我想您正在嘗試刪除HN文章,這是我的建議:

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//td[@class="title"]')
    items = []
    for title in titles:
        item = HackernewsItem()
        item["title"] = title.select("a/text()").extract()
        item["url"] = title.select("a/@href").extract()
        item["score"] = title.select('../td[@class="subtext"]/span/text()').extract()
        items.append(item)
    return items

我沒有測試它,但是它將給您一個想法。

Python 2.7中的CSV模塊不支持Unicode,因此建議改用unicodecsv

$pip install unicodecsv

unicodecsv是Python 2的csv模塊的直接替代品,該模塊支持Unicode字符串而沒有麻煩。

然后用它代替import csv

import unicodecsv as csv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM