实现步骤
- 创建爬虫项目
- 根据需求定义数据模型
- 实现爬虫
- 保存爬取的数据
- 实现随机user-agent和代理ip下载器中间件,解决ip反爬
实现爬虫的具体步骤
- url url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=失信被执行人'
- 测试,如果不成功,可能是需要设置请求头
- 请求方式 get
- 参数
- 请求头 user-agent referer
- 返回数据个数
- 如何翻页
- 有时候不用获取url翻页,根据请求中的翻页参数,可以for循环请求
- url url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=失信被执行人'
保存失信名单信息
创建数据库,创建表
在settings中配置数据库信息
- host、port、db、user、password
实现管道类
在open_spider中,建立数据库连接,获取cursor
def open_spider(self, spider): """不用做判断,因为三只爬虫的爬取结果全部放到同一个数据库里边""" # 创建数据库连接 self.connection = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, db=MYSQL_DB, user=MYSQL_USER, password=MYSQL_PASSWORD) # 获取游标 self.cursor = self.connection.cursor()
在close_spider中,关闭cursor,关闭数据库连接
def close_spider(self, spider): # 关闭游标 self.cursor.close() # 关闭连接 self.connection.close()
在process_item中,如果数据不存在,保存数据
def process_item(self, item, spider): # 存储过程,最重要是判断数据是否已经存在 # 判断数据是否已经存在 if item['age'] == 0: select_count_sql = "select count(1) from dishonest where name='{}' and area='{}'".format(item['name'], item['area']) else: select_count_sql = "select count(1) from dishonest where card_num='{}'".format(item['card_num']) # 执行查询 self.cursor.execute(select_count_sql) count = self.cursor.fetchone()[0] # 游标会获取的结果是列表形式 # 根据查询结果,决定是否插入数据 if count == 0: keys, values = zip(*dict(item).items()) insert_sql = 'insert into dishonest ({}) values ({})'.format( ','.join(keys), ','.join(['%s']*len(values)) ) self.cursor.execute(insert_sql,values) self.connection.commit() spider.logger.info('插入数据') else: spider.logger.info('数据重复')
在settings.py中开启管道
爬取失信人名单
猜你喜欢
转载自www.cnblogs.com/hui-code/p/12030353.html
今日推荐
周排行