zoukankan      html  css  js  c++  java
  • Python爬虫开发【第1篇】【Scrapy shell】

    Scrapy Shell

    Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据。

    启动Scrapy Shell

    进入项目的根目录,执行下列命令来启动shell:

    scrapy shell "http://www.itcast.cn/channel/teacher.shtml"  

    Scrapy Shell根据下载的页面会自动创建一些方便使用的对象,例如: Response对象、 Selector 对象 (对HTML及XML内容)

    • 当shell载入后,将得到一个包含response数据的本地 response变量,输入 response.body将输出response的包体,输出 response.headers 可以看到response的包头。

    • 输入 response.selector 时, 将获取到一个response 初始化的类 Selector 的对象,此时可以通过使用 response.selector.xpath()response.selector.css() 来对 response 进行查询。

    • Scrapy也提供了一些快捷方式, 例如 response.xpath()response.css()同样可以生效(如之前的案例)。 

    Selectors选择器

    Scrapy Selectors 内置 XPath 和 CSS Selector 表达式机制

    Selector有四个基本的方法,最常用的还是xpath:

    • xpath(): 传入xpath表达式,返回该表达式所对应的所有节点的selector list列表
    • extract(): 序列化该节点为Unicode字符串并返回list
    • css(): 传入CSS表达式,返回该表达式所对应的所有节点的selector list列表,语法同 BeautifulSoup4
    • re(): 根据传入的正则表达式对数据进行提取,返回Unicode字符串list列表

    XPath表达式的例子及对应的含义:

    /html/head/title: 选择<HTML>文档中 <head> 标签内的 <title> 元素
    /html/head/title/text(): 选择上面提到的 <title> 元素的文字
    //td: 选择所有的 <td> 元素
    //div[@class="mine"]: 选择所有具有 class="mine" 属性的 div 元素

    Selector爬取腾讯社招网站:

    地址:http://hr.tencent.com/position.php?&start=0#a

    # 启动
    scrapy shell "http://hr.tencent.com/position.php?&start=0#a"
    
    # 返回 xpath选择器对象列表
    response.xpath('//title')
    [<Selector xpath='//title' data=u'<title>u804cu4f4du641cu7d22 | u793eu4f1au62dbu8058 | Tencent u817eu8bafu62dbu8058</title'>]
    
    # 使用 extract()方法返回 Unicode字符串列表
    response.xpath('//title').extract()
    [u'<title>u804cu4f4du641cu7d22 | u793eu4f1au62dbu8058 | Tencent u817eu8bafu62dbu8058</title>']
    
    # 打印列表第一个元素,终端编码格式显示
    print response.xpath('//title').extract()[0]
    <title>职位搜索 | 社会招聘 | Tencent 腾讯招聘</title>
    
    # 返回 xpath选择器对象列表
    response.xpath('//title/text()')
    <Selector xpath='//title/text()' data=u'u804cu4f4du641cu7d22 | u793eu4f1au62dbu8058 | Tencent u817eu8bafu62dbu8058'>
    
    # 返回列表第一个元素的Unicode字符串
    response.xpath('//title/text()')[0].extract()
    u'u804cu4f4du641cu7d22 | u793eu4f1au62dbu8058 | Tencent u817eu8bafu62dbu8058'
    
    # 按终端编码格式显示
    print response.xpath('//title/text()')[0].extract()
    职位搜索 | 社会招聘 | Tencent 腾讯招聘
    
    response.xpath('//*[@class="even"]')
    职位名称:
    
    print site[0].xpath('./td[1]/a/text()').extract()[0]
    TEG15-运营开发工程师(深圳)
    职位名称详情页:
    
    print site[0].xpath('./td[1]/a/@href').extract()[0]
    position_detail.php?id=20744&keywords=&tid=0&lid=0
    职位类别:
    
    print site[0].xpath('./td[2]/text()').extract()[0]
    

    官方文档:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/shell.html

    Item Pipeline

    当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item。

    Item Pipeline的典型应用:

    • 验证爬取的数据(检查item包含某些字段,比如说name字段)
    • 查重(并丢弃)
    • 将爬取结果保存到文件或者数据库中

    Item Pipeline编写

    item pipiline组件是一个独立的Python类,其中process_item()方法必须实现:

    import something
    
    class SomethingPipeline(object):
        def __init__(self):    
            # 可选实现,做参数初始化等
            # doing something
    
        def process_item(self, item, spider):
            # item (Item 对象) – 被爬取的item
            # spider (Spider 对象) – 爬取该item的spider
            # 这个方法必须实现,每个item pipeline组件都需要调用该方法,
            # 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。
            return item
    
        def open_spider(self, spider):
            # spider (Spider 对象) – 被开启的spider
            # 可选实现,当spider被开启时,这个方法被调用。
    
        def close_spider(self, spider):
            # spider (Spider 对象) – 被关闭的spider
            # 可选实现,当spider被关闭时,这个方法被调用
    

    完善之前的案例:

    item写入JSON文件

    以下pipeline将所有(从所有'spider'中)爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':

    import json
    
    class ItcastJsonPipeline(object):
    
        def __init__(self):
            self.file = open('teacher.json', 'wb')
    
        def process_item(self, item, spider):
            content = json.dumps(dict(item), ensure_ascii=False) + "
    "
            self.file.write(content)
            return item
    
        def close_spider(self, spider):
            self.file.close()
    

    启用一个Item Pipeline组件

    为了启用Item Pipeline组件,必须将它的类添加到 settings.py文件ITEM_PIPELINES 配置,就像下面这个例子:

    # Configure item pipelines
    # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
    ITEM_PIPELINES = {
        #'mySpider.pipelines.SomePipeline': 300,
        "mySpider.pipelines.ItcastJsonPipeline":300
    }
    

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

    重新启动爬虫

    将parse()方法改为4.2中最后思考中的代码,然后执行下面的命令:

    scrapy crawl itcast
    

    查看当前目录是否生成teacher.json

  • 相关阅读:
    uni-app之预加载和取消预加载(仅支持APP和H5)——uni.preloadPage、uni.unPreloadPage
    JavaScript 之数组对象(Array)
    【2019csp模拟】文件列表
    【2019csp模拟】两段子序列
    B. 【普转提七联测 Day 6】载重
    C.【普转提七联测 Day 6】分数
    A. 【普转提七联测 Day 6】石头
    struct和class的区别
    TagHelper中获取当前Url
    为什么要使用 Taghelper (标记助手)
  • 原文地址:https://www.cnblogs.com/loser1949/p/9462712.html
Copyright © 2011-2022 走看看