【发布时间】:2017-11-08 16:45:05
【问题描述】:
我想使用 scrapy 从网站上抓取评论数据。代码如下。
问题是每次程序进入下一页时,它都会从头开始(由于回调)并重置records[]。因此数组将再次为空,并且保存在records[] 中的每条评论都将丢失。这导致当我打开我的 csv 文件时,我只得到最后一页的评论。
我想要的是所有数据都存储在我的 csv 文件中,这样records[] 就不会在每次请求下一页时都重新设置。我不能在 parse 方法之前放行:records = [],因为没有定义数组。
这是我的代码:
def parse(self, response):
records = []
for r in response.xpath('//div[contains(@class, "a-section review")]'):
rtext = r.xpath('.//div[contains(@class, "a-row review-data")]').extract_first()
rating = r.xpath('.//span[contains(@class, "a-icon-alt")]/text()').extract_first()
votes = r.xpath('normalize-space(.//span[contains(@class, "review-votes")]/text())').extract_first()
if not votes:
votes = "none"
records.append((rating, votes, rtext))
print(records)
nextPage = response.xpath('//li[contains(@class, "a-last")]/a/@href').extract_first()
if nextPage:
nextPage = response.urljoin(nextPage)
yield scrapy.Request(url = nextPage)
import pandas as pd
df = pd.DataFrame(records, columns=['rating' , 'votes', 'rtext'])
df.to_csv('ama.csv', sep = '|', index =False, encoding='utf-8')
【问题讨论】:
标签: python csv callback scrapy