编写qsbk_spider.py爬虫文件

# -*- coding: utf-8 -*-
import scrapy
from qsbk.items import QsbkItem
from scrapy.http.response.html import HtmlResponse
from scrapy.selector.unified import SelectorList

class QsbkSpiderSpider(scrapy.Spider):
    name = 'qsbk_spider'
    allowed_domains = ['qiushibaike.com']
    start_urls = ['https://www.qiushibaike.com/text/']

    def parse(self, response):
        duanzidiv=response.xpath("//div[@id='content-left']/div")
        for duanzidivs in duanzidiv:
            author=duanzidivs.xpath(".//h2/text()").get().strip()
            content=duanzidivs.xpath(".//div[@class='content']//text()").getall()
            content="".join(content).strip()
           #调用pipelines文件,存取数据到json文件里面
            # duanzi={"author":author,"content":content}
            item=QsbkItem(author=author,content=content)
            yield item

编写items.py文件

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class QsbkItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author=scrapy.Field()
    content=scrapy.Field()

编写pipelines.py文件保存数据到duanzi.json文件里

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
class QsbkPipeline(object):
    def __init__(self):
        self.fp=open("duanzi.json",'w',encoding='utf-8')

    def open_spider(self,spider):
        print("爬虫开始了...")

    def process_item(self, item, spider):
        item_json=json.dumps(dict(item),ensure_ascii=False)
        self.fp.write(item_json+'\n')
        return item

    def close_spider(self,spider):
        self.fp.close()
        print("爬虫结束了...")

编写start.py爬虫启动文件

# -*- coding:utf-8 -*-
#作者:    baikai
#创建时间: 2018/12/14 9:16
#文件:    start.py
#IDE:    PyCharm
from scrapy import cmdline

# cmdline.execute("scrapy crawl shuju_spider".split())
cmdline.execute(["scrapy","crawl","qsbk_spider"])

设置settings.py文件相关配置

运行start.py文件爬取网站数据并保存到duanzi.json文件里

# Scrapy笔记
## 安装scrapy框架:
1. 安装`scrapy`:通过`pip install scrapy`即可安装。
2. 如果在windows下,还需要安装`pypiwin32`,如果不安装,那么以后运行scrapy项目的时候就会报错。安装方式:`pip install pypiwin32`。
3. 如果是在ubuntu下,还需要安装一些第三方库:`sudo apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev`。

## 创建项目和爬虫:
1. 创建项目:`scrapy startproject [爬虫的名字]`。
2. 创建爬虫:进入到项目所在的路径,执行命令:`scrapy genspider [爬虫名字] [爬虫的域名]`。注意,爬虫名字不能和项目名称一致。

## 项目目录结构:
1. items.py:用来存放爬虫爬取下来数据的模型。
2. middlewares.py:用来存放各种中间件的文件。
3. pipelines.py:用来将items的模型存储到本地磁盘中。
4. settings.py:本爬虫的一些配置信息(比如请求头、多久发送一次请求、ip代理池等)。
5. scrapy.cfg:项目的配置文件。
6. spiders包:以后所有的爬虫,都是存放到这个里面。

## 糗事百科Scrapy爬虫笔记:
1. response是一个`scrapy.http.response.html.HtmlResponse`对象。可以执行`xpath`和`css`语法来提取数据。
2. 提取出来的数据,是一个`Selector`或者是一个`SelectorList`对象。如果想要获取其中的字符串。那么应该执行`getall`或者`get`方法。
3. getall方法:获取`Selector`中的所有文本。返回的是一个列表。
4. get方法:获取的是`Selector`中的第一个文本。返回的是一个str类型。
5. 如果数据解析回来,要传给pipline处理。那么可以使用`yield`来返回。或者是收集所有的item。最后统一使用return返回。
6. item:建议在`items.py`中定义好模型。以后就不要使用字典。
7. pipeline:这个是专门用来保存数据的。其中有三个方法是会经常用的。
    * `open_spider(self,spider)`:当爬虫被打开的时候执行。
    * `process_item(self,item,spider)`:当爬虫有item传过来的时候会被调用。
    * `close_spider(self,spider)`:当爬虫关闭的时候会被调用。
    要激活piplilne,应该在`settings.py`中,设置`ITEM_PIPELINES`。示例如下:
    ```python
    ITEM_PIPELINES = {
       'qsbk.pipelines.QsbkPipeline': 300,
    }
    ```

## JsonItemExporter和JsonLinesItemExporter:
保存json数据的时候,可以使用这两个类,让操作变得得更简单。
1. `JsonItemExporter`:这个是每次把数据添加到内存中。最后统一写入到磁盘中。好处是,存储的数据是一个满足json规则的数据。坏处是如果数据量比较大,那么比较耗内存。示例代码如下:
    ```python
    from scrapy.exporters import JsonItemExporter

    class QsbkPipeline(object):
        def __init__(self):
            self.fp = open("duanzi.json",'wb')
            self.exporter = JsonItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
            self.exporter.start_exporting()

        def open_spider(self,spider):
            print('爬虫开始了...')

        def process_item(self, item, spider):
            self.exporter.export_item(item)
            return item

        def close_spider(self,spider):
            self.exporter.finish_exporting()
            self.fp.close()
            print('爬虫结束了...')
    ```
2. `JsonLinesItemExporter`:这个是每次调用`export_item`的时候就把这个item存储到硬盘中。坏处是每一个字典是一行,整个文件不是一个满足json格式的文件。好处是每次处理数据的时候就直接存储到了硬盘中,这样不会耗内存,数据也比较安全。示例代码如下:
    ```python
    from scrapy.exporters import JsonLinesItemExporter
    class QsbkPipeline(object):
        def __init__(self):
            self.fp = open("duanzi.json",'wb')
            self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')

        def open_spider(self,spider):
            print('爬虫开始了...')

        def process_item(self, item, spider):
            self.exporter.export_item(item)
            return item

        def close_spider(self,spider):
            self.fp.close()
            print('爬虫结束了...')
    ```

python scrapy实战糗事百科保存到json文件里的更多相关文章

  1. 新手学习爬虫之创建第一个完整的scrapy工程-糗事百科

    创建第一个scrapy工程-糗事百科 最近不少小伙伴儿,问我关于scrapy如何设置headers的问题,时间久了不怎么用,还真有的忘,全靠记忆去写了,为了方便大家参考,也方便我以后的查阅,这篇文章就 ...

  2. 关于爬取数据保存到json文件,中文是unicode解决方式

    流程: 爬取的数据处理为列表,包含字典.里面包含中文, 经过json.dumps,保存到json文件中, 发现里面的中文显示未\ue768这样子 查阅资料发现,json.dumps 有一个参数.ens ...

  3. python 爬取糗事百科 gui小程序

    前言:有时候无聊看一些搞笑的段子,糗事百科还是个不错的网站,所以就想用Python来玩一下.也比较简单,就写出来分享一下.嘿嘿 环境:Python 2.7 + win7 现在开始,打开糗事百科网站,先 ...

  4. Python爬取糗事百科

    import urllib import urllib.request from bs4 import BeautifulSoup """     1.抓取糗事百科所有纯 ...

  5. python 抓取糗事百科糗图

    1 首先看下要抓取的页面 这是糗事百科里面的糗图页面,每一页里面有很多的图片,我们要做的就是把这些图片抓取下来. 2 分析网页源代码 发现源代码里面的每张图是这样储存的,所以决定使用正则匹配出图片的u ...

  6. Python抓取糗事百科成人版图片

    最近开始学习爬虫,一开始看的是静觅的爬虫系列文章,今天看到糗事百科成人版,心里就邪恶了一下,把图片都爬下来吧,哈哈~ 虽然后来实现了,但还是存在一些问题,暂且不提,先切入正题吧,没什么好说的,直接上代 ...

  7. python爬取糗事百科段子

    初步爬取糗事百科第一页段子(发布人,发布内容,好笑数和评论数) #-*-coding:utf--*- import urllib import urllib2 import re page = url ...

  8. <爬虫实战>糗事百科

    1.糗事百科段子.py # 目标:爬取糗事百科段子信息(文字) # 信息包括:作者头像,作者名字,作者等级,段子内容,好笑数目,评论数目 # 解析用学过的几种方法都实验一下①正则表达式.②Beauti ...

  9. Python爬虫_糗事百科

    本爬虫任务: 爬虫糗事百科网站(https://www.qiushibaike.com/)--段子版块中所有的[段子].[投票数].[神回复]等内容 步骤: 通过翻页寻找url规律,构造url列表 查 ...

随机推荐

  1. Lombok使用与问题

    前言 想想已经工作了一年,工作中遇到的问题一直没有记录下来,以后遇到相同的问题可能还需要花费很多的时间,因此打算记录一下博客.方便以后自己的复习和问题查找 刚好最近项目引入了Lombok,刚好从现在起 ...

  2. Spring课程 Spring入门篇 1-1Spring入门课程简介

    课程链接: 课程简介: 1 什么是框架 2 Spring简介 3 IOC(配置,注解) 4 Bean(配置,注解) 5 AOP(配置,注解,AspectJ.API) SpringFrameWork 常 ...

  3. Hibernate课程 初探多对多映射1-1 多对多应用场景

    1 用途: 员工和项目之间的多对多关系 2 实现: 员工表和项目表之外,建立员工和项目关联表来实现: 3 hibernate应用: set元素和many-to-many来实现

  4. [RabbitMQ]Windows环境下rabbitmqclt(Command Line Tools)出现Erlang distribution failed错误的解决方法

    摘要 当使用rabbitmqctl时出现Erlang distribution failed,把%SystemRoot%Windows\System32\config\systemprofile下的. ...

  5. 也谈ThreadLocal

    欢迎赐教博客地址(http://www.cnblogs.com/shizhongtao/p/5358411.html) 对于ThreadLocal使用,网上一堆一堆的.什么内存泄露,什么线程不安全.这 ...

  6. python下载文件

    import urllib import urllib2 import requests url = "http://www.blog.pythonlibrary.org/wp-conten ...

  7. HashWithIndifferentAccess

    The params method returns the parameters passed to the action, such as those fromthe form or query p ...

  8. 再谈 Struts1.x 的运行机制

    1.Action类 execute 方法 ActionMapping 对应 <action path="user" type="myuser.UserAction& ...

  9. Azure 6 月新公布

    Azure 6 月新发布:磁盘加密预览版 , CDN 用户上传 HTTPS 自有证书及价格调整. Azure 磁盘加密预览版现已在中国发布 Azure 磁盘加密预览版已对 Azure 中国云地区的 W ...

  10. Node.js-npm安装包目录修改

    请借我一个哭的表情....=.= 等我发现的时候为时已晚~所有安装的包都去了C盘,而强迫症的我想卸载了之前所有的包再重新下一遍!!! 切记!安装好npm后,记得修改: 原始路径: 修改后的路径(如果没 ...