最近在写爬虫爬取APP的时候通过scrapy的pipelines插入数据库,返回一次item 便插入一条数据,发现运行速度非常慢,一天只爬取了几万条数据。之前记得学习爬虫时,老师曾经提过,每条数据都插入会造成爬取速度非常慢。
所以我改进了一下自己的代码,选择批量插入数据库。每次往数据库中写入1000条数据,代码运行效率有大幅度的提升。本次使用的scrapy+pymysql。下面是我的代码。
在我们创建scrapy工程时会默认创建一个pipelines,我们只需要对这个pipelines进行修改就可以了。
class AppPipeline(object):
data_list = []
def __init__(self):
host = 'xxxxx'
user = 'yourusername'
password = 'yourpassword'
database = 'yourdb'
charset = 'utf8'
self.conn = pymysql.Connect(host=host, user=user, password=password, database=database, charset=charset)
self.cur = self.conn.cursor()
def open_spider(self,spider):
#如果