python爬虫深层次,全程的编码和使用

爬虫整个过程中,需要蜘蛛,调度器,下载器,管道 的配合,才能真正完成整个操作,今天就来说一说这个过程以及编码和使用过程:

本章主要了解一下item和pipline的运用

(注意:在使用item的前提是,将setting文件中的ITEM_PIPELINES释放

ITEM_PIPELINES = {
   'kgc.pipelines.KgcPipeline': 300,
}

  代码预览:

spider.py

import scrapy
from kgc.items import *


class KgcspideSpider(scrapy.Spider):
    name = 'kgcspide'
    start_urls = ['http://www.kgc.cn/list/230-1-6-9-9-0.shtml']

    def parse(self, response):
        title = response.css('a.yui3-u.course-title-a.ellipsis::text').extract()
        price=response.css('div.right.align-right>span::text').extract()
        persons=response.css('span.course-pepo::text').extract()
       
        datas=zip(title,price,persons)
        for d in datas:
            item=KgcItem()
            item['title']=d[0]
            item['price']=d[1]
            item['persons']=d[2]
            yield  item
        next_url=response.css('下一页的地址css样式')
     if next_url is not None:
       yiele response.follow(next_url,self.parse)

精解:spider文件是爬虫的主体,可以在这里编写你想要爬取数据的方式和类型。用css样式获取的title,price,persons,用zip 形式进行压缩后,,对其进行循环输出,当然,首先要创建文件所在包的item对象,依次输出,然后用生成器生成item,如果需要进行对接下来页码的爬取,只需要判断后,再次调用parse函数即可。

itme.py文件

import scrapy


class KgcItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title=scrapy.Field()
    price=scrapy.Field()
    persons=scrapy.Field()

精解:item文件是用来存储爬取的数据的,里面运用scrapy的Field方法来存储。

piplines.py文件

class KgcPipeline(object):
    def open_spider(self,spider):
        #当蜘蛛启动时自动执行
        self.file=open("kgc.csv","w",encoding='utf8')
    def process_item(self, item, spider):
        #蜘蛛每yild一个item,执行一次
        line=item["title"]+","+item["price"]+','+item["persons"]+'\n'
        self.file.write(line)
        return item
    def close_spider(self,spider):
        #蜘蛛完成工作关闭执行
        self.file.close()

精解:piplines文件是对spider文件的过滤,并对数据的储存路径进行定制。三个函数,第一个open_spider在spider开始的时候执行,在这个函数中我们一般会连接数据库,为数据存储做准备。process_item函数在捕捉到item的时候执行,一般我们会在这里做数据过滤并且把数据存入数据库。close_spider在spider结束的时候执行,一般用来断开数据库连接或者做数据收尾工作。这里我们没有连接数据库,只是用一个kgc.csv的文件来存储数据。

说在最后的:

对于爬虫的编写,最主要的还是spider的编写,在这里,你可以用你自己喜欢的方式进行编译,使得数据的爬取按照你自己想要的方式和类型以及其他更加优秀的方法进行。如果各位有什么好的建议或意见,欢迎积极留言讨论,每周二和周四下午都会进行博客更新。

猜你喜欢

转载自www.cnblogs.com/qianshuixianyu/p/9230001.html
今日推荐