繁体   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