scrapy框架将数据写入txt出现数据丢失

分析:

获取网页中的数据可以成功爬取,但是在写入txt操作的时候部分数据丢失。可能原因是scrapy框架是异步爬取数据,所以写入数据的时候不能完全写入完整的数据。

解决方法:

一、代码
  • pipelines.py
# 开启爬虫前调用
def open_spider(self, spider):
    self.file = open(r'novels/dhzmg.txt', 'w', encoding='utf-8')

# parse()返回值时调用,一般在这里写入数据
def process_item(self, item, spider):
    try:
        res = dict(item)
        title = res['title']
        line = res['data']
        self.file.write(title+'\n'+line+'\n\n')
   except:
        pass

# 关闭爬虫后调用,此处用于关闭文件连接
def close_spider(self, spider):
    self.file.close()

说明:
- open_spider(): 开启爬虫前调用,可用于创建连接对象;
- close_spider():关闭爬虫后调用,可以用于关闭文件连接;
- process_item():此函数用于写入数据操作,在parse()返回值的时候自动调用。

二、配置

使用pipeline.py文件中的方法时,需要在setting.py更改设置。

  • setting.py
ITEM_PIPELINES = {
    
    
   'myscrapy.pipelines.MyscrapyPipeline': 300,
}

找到这个配置,取消前面的注释即可。

猜你喜欢

转载自blog.csdn.net/qq_42349944/article/details/102680166