爬虫---scrapy框架

什么是scrapy:

组成部分:引擎:调度器,下载器,爬虫模块,管道存储数据,下载中间件,spider中间件

步骤:

        引擎---队列--引擎,

        引擎---下载----外部服务器请求源码---引擎,

        引擎---爬虫提取数据item对象---引擎---pipe去重存储

 

安装:

       cmd中进入虚拟环境workon env1
       pip install  老师的文件直接拉过来()
       pip install  老师的文件直接拉过来()
       pip install Scrapy

测试是否成功:
     >scrapy
     >pip list
 

1.项目创建:

        >scrapy startproject JobSpider

2.创建爬虫: 放入jobSpider /spiders/ 

     >cd JobSpider
     >scrapy genspider pythonPosition 51job.com

    # scrapy genspider 名字   域名(创建之后可修改)

3.执行命令爬取网页源码:
"第一种方法在cmd中"
>scrapy crawl pythonPosition
第二种方法
在jobSpider/下创建run.py写入代码运行

响应对象属性:

name:定义 spider 名字的字符串,

allowed_domains:包含了 spider 允许爬取的域名(domain)的列表,可选。

start_urls:初始 URL 元祖/列表。当没有制定特定的 URL 时,spider 将从该列表中开始迚行爬取

parse(self, response):当请求 url 返回网页没有指定回调函数时,默认的 Request 对象回调函数。用来处理网
页返回的 response,以及生成 Item 戒者 Request 对象。

log(self, message[, level, component]):使用 scrapy.log.msg() 方法记录(log)message。

响应对象选择器:

 meta:请求和响应之间传递数据,

请求对象参数: 
url: 用于请求的 URL
callback:指定一个回调函数,该回调函数以这个 request 对应的 response 作为第一个参
数。如果未指定 callback,则默认使用 spider 的 parse()方法。
method:HTTP 请求的方法,默认为 GET
meta:指定 Request.meta 属性的初始值,字典类型。可以在回调函数们之间传递参数
body:请求体
headers:request 的头信息。
cookies:cookie
encoding:请求的编码, 默认为 utf-8
priority:请求的优先级

dont_filter = :生成一个指纹放入set集合(url去重)

dont_filter(boolean):指定该请求是否被 Scheduler 过滤。该参数可以是 request 重复使
用(Scheduler 默认过滤重复请求)。谨慎使用!!

默认去重过滤:dont_filter = Flase

errback:处理异常的回调函数。

Item Pipeline

当 Item 在 Spider 中被收集之后,它将会被传递到 Item Pipeline,这些 Item Pipeline
组件按定义的顺序处理 Item。
每个 Item Pipeline 都是实现了简单方法的 Python 类,比如决定此 Item 是丢弃而存储。
item pipeline 的一些典型应用:
       1. 验证爬取的数据(检查 item 包含某些字段,比如说 name 字段)
       2. 查重(并丢弃)
        3.将爬取结果保存到文件或者数据库中 

启用一个 Item Pipeline 组件

为了启用 Item Pipeline 组件,必须将它的类添加到 settings.py 文件 ITEM_PIPELINES 
配置,比如:
ITEM_PIPELINES = {
 #'mySpider.pipelines.SomePipeline': 300,
 "mySpider.pipelines.JsonPipeline":300
}

分配给每个类的整型值,确定了他们运行的顺序,item 按数字从低到高的顺序通过
pipeline,通常将这些数字定义在 0-1000 范围内(0-1000 随意设置,数值越低,组件
的优先级越高)

优先级越高先处理

Selectors 选择器

Scrapy 提取数据有自己的一套机制。它们被称作选择器(seletors),
Selector 有四个基本的方法,最常用的还是 xpath:
xpath(): 传入 xpath 表达式,返回该表达式所对应的所有节点的 selector list 列表
extract(): 序列化该节点为 Unicode 字符串并返回 list
css(): 传入 CSS 表达式,返回该表达式所对应的所有节点的 selector list 列表,诧法同
BeautifulSoup4
re(): 根据传入的正则表达式对数据迚行提取,返回 Unicode 字符串 list 列表

 

 

import scrapy


class PythonpositionSpider(scrapy.Spider):
    "爬虫名字"
    name = 'pythonPosition'
    "限定爬取域名"
    allowed_domains = ['51job.com']
    "列出了要爬取的url地址"
    start_urls = ['https://search.51job.com/list/020000,000000,0000,00,9,99,Python,2,1.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=']

    "重载:同一个类中,方法名相同,"
    "重写父类的方法"
    def parse(self, response):
        """
        数据的解析提取
        :param response:
        :return:
        """
        self.log("content:")
        # print("content:", response.body)
        job_list = response.xpath('//div[@class="dw_table"]/div[@class="el"]')
        print("len:", len(job_list))
        for each in job_list:
            name = each.xpath('./p/span/a/text()').extract()[0].strip()
            print("职位名称:", name)
            crop = each.xpath('./span[1]/a/text()').extract()[0].strip()
            print("公司:", crop)
            city = each.xpath('./span[2]/text()').extract()[0].strip()
            print("城市:", city)
            salary = each.xpath('./span[3]/text()')
            if len(salary) > 0:
                salary = salary.extract()[0].strip()
            else:
                salary = "空"
            print("薪资:", salary)
            time = each.xpath('./span[4]/text()').extract()[0].strip()
            print("发布时间:", time)

 run.py文件:

"执行文件"
from scrapy import cmdline

name = 'pythonPosition'
cmd = 'scrapy crawl {0}'.format(name)

"执行命令,切割为列表"
cmdline.execute(cmd.split())

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值