我只是想写入 csv。但是,我有两个单独的 for 语句,因此每个 for 语句的数据独立导出并破坏顺序。建议?
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 语句打印在其他语句的下方,而不是像 header 那样打印在“其中”。
CSV image attached:
以及完整文件的 github 链接:https://github.com/nchlswtsn/scrapy/blob/master/items.csv 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
我没有测试它,但它会给你一个想法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)