scrapy简单使用方法

1.创建项目:
scrapy startproject 项目名
例如:
scrapy startproject baike

windows下,cmd进入项目路径例如
d:\pythonCode\spiderProject>scrapy startproject baidubaike
将创建项目名为 baidubaike

2.使用命令创建一个爬虫:
scrapy genspider 爬虫名称 需要爬取的网址
scrapy genspider baike baike.baidu.com

注意:爬虫名称不能和项目名相同

d:\pythonCode\spiderProject\baidubaike>scrapy genspider baike baike.baidu.com

命令执行后将在d:\pythonCode\spiderProject\baidubaike\baidubaike\spiders\下,生成baike.py

3.修改baike.py文件

import scrapy
from baidubaike.items import BaidubaikeItem
from scrapy.http.response.html import HtmlResponse
from scrapy.selector.unified import SelectorList

class BaikeSpider(scrapy.Spider):
     #爬虫名称
     name = 'baike'
     #需要爬取的网址
     allowed_domains = ['baike.baidu.com']
     #起始网址
     start_urls = ['https://baike.baidu.com/art/%E6%8B%8D%E5%8D%96%E8%B5%84%E8%AE%AF']

def parse(self, response):
             uls = response.xpath("//div[@class='list-content']/ul")
             for ul in uls:
                   lis = ul.xpath(".//li")
                   #print(lis)
                   for li in lis:
                         title = li.xpath(".//a/text()").get()
                         time = li.xpath(".//span/text()").get()
                         item = BaidubaikeItem(title=title, time=time)
                         yield item

4.items.py

import scrapy

class BaidubaikeItem(scrapy.Item):
       # define the fields for your item here like:
       # name = scrapy.Field()
       # pass
       title = scrapy.Field()
       time = scrapy.Field()

5.修改settings.py文件
1)开启 DEFAULT_REQUEST_HEADERS
修改如下
DEFAULT_REQUEST_HEADERS = {
     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
     'Accept-Language': 'en',
     'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}

2)将 ROBOTSTXT_OBEY = True 改为 ROBOTSTXT_OBEY = False
说明:
默认为True,就是要遵守robots.txt 的规则
将此配置项设置为 False ,拒绝遵守 Robot协议

3)开启 ITEM_PIPELINES
ITEM_PIPELINES = {
     'baidubaike.pipelines.BaidubaikePipeline': 300,
}
其中,ITEM_PIPELINES是一个字典文件,键为要打开的ItemPipeline类,值为优先级,ItemPipeline是按照优先级来调用的,值越小,优先级越高。

6.修改pipelines.py文件
# -*- 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 BaidubaikePipeline(object):
#        def __init__(self):
#               #pass
#               self.fp = open('baike.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('爬虫结束了。。')
#

#第二种方式
#from scrapy.exporters import JsonItemExporter
#
#class BaidubaikePipeline(object):
#        def __init__(self):
#               #pass
#               self.fp = open('baike.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('爬虫结束了。。')

#第三种方式
from scrapy.exporters import JsonLinesItemExporter

class BaidubaikePipeline(object):
      def __init__(self):
            #pass
            self.fp = open('baike.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('爬虫结束了。。')

7.运行爬虫
scrapy crawl 爬虫名

d:\pythonCode\spiderProject\baidubaike\baidubaike>scrapy crawl baike

scrapy简单使用方法的更多相关文章

  1. scrapy爬虫学习系列二:scrapy简单爬虫样例学习

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  2. crawlscrapy简单使用方法

    crawlscrapy简单使用方法 1.创建项目:scrapy startproject 项目名例如:scrapy startproject wxapp windows下,cmd进入项目路径例如d:\ ...

  3. MySQL笔记-最简单的方法来解决找不到mysqld.sock文件的问题

    首先,环境:ubuntu 14.04,采用apt-get的方式安装的,手动安装可能路径设置稍有区别. 1.安装MySQL后,用命令行首次启动时发现找不到Mysqld.sock文件,提示: ERROR ...

  4. mfc显示静态图片最简单的方法

    一致都是研究如何调用opencv显示动态图片,但是很多时候在显示图标的时候,都是需要显示静态图片,现在将最简单的方法总结下: 1.添加picture控件 2.添加资源,要求为bmp 3.修改属性 结果 ...

  5. ECshop设置301最快捷最简单的方法

    ECshop设置301最快捷最简单的方法 在 init.php中加入以下代码 if (strtolower($_SERVER['SERVER_NAME'])!='www.fz1688.com') { ...

  6. git 的简单使用方法

    git 的简单使用方法1. 服务器 安装完成2. ssh 中的账号创建完成3. 创建 ssh 账号,会在 ssh 的安装目录下的home 目录里面,多了用户家目录4. 进入该目录 ,创建一个新的文件夹 ...

  7. JavaScript,一个超级简单的方法判断浏览器的内核前缀

    先说明,此处的方法是说超级简单的方法,不是指代码超级少,而是用非常简单的知识点,只要懂得怎么写JavaScript的行内样式就可以判断. 大家应该还记得JavaScript行内样式怎么写吧?(看来我是 ...

  8. NET MVC1项目升级到MVC2最简单的方法

    NET MVC1项目升级到MVC2最简单的方法 把MVC1项目升级到MVC2,最简单的做法如下: 新建MVC2项目 新建一个MVC2项目,把原来MVC1的项目文件全部拷贝到新建MVC2项目目录里,依照 ...

  9. js 获取当天23点59分59秒 时间戳 (最简单的方法)

    js 获取当天23点59分59秒 时间戳 (最简单的方法) new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60* ...

随机推荐

  1. 总结在ssm整合中,Mybatis出现Mapped Statements collection already contains value for xxxxx的解决方案

    先贴一段报错信息: 前面的都不是很重要,看最后灰色标注的那段.... 严重: 异常将上下文初始化事件发送到类的侦听器实例.[org.springframework.web.context.Contex ...

  2. NumPy数据的归一化

    数据的归一化 首先我们来看看归一化的概念: 数据的标准化(normalization)和归一化 数据的标准化(normalization)是将数据按比例缩放,使之落入一个小的特定区间.在某些比较和评价 ...

  3. bay——linux6.5-PV-LV-VG扩容.txt

    [root@rac2 cdrom]# export LANG=en_US[root@rac2 cdrom]# lsblk[root@rac2 cdrom]# lvscan --- 查看系统PV LV ...

  4. 如何确定UNDO_RETENTION参数的值以避免ORA-1555 (Doc ID 822411.1)

    How to Determine the Value Of UNDO_RETENTION Parameter to Avoid ORA-1555 (Doc ID 822411.1) APPLIES T ...

  5. Linux:DNS服务器搭建

    DNS简介 DNS(Domain Name System)域名系统: 是一种采用客户端/服务器机制,负责实现计算机名称与IP地址转换的系统.DNS作为一种重要的网络服务,既是国际互联网工作的基础,同时 ...

  6. 程序运行时间测试 - 使用系统函数 getrusage 获取程序运行时间

    https://github.com/yaowenxu/Workplace/blob/master/timer/getrusagetimer.c 关键结构体: struct rusage { stru ...

  7. Linux系统学习 三、网络基础—虚拟机网络配置

    Linux网络基础 Linux的ip地址配置 Linux网络配置文件 常用网络命令 虚拟机网络参数配置 1.配置Linux的IP地址 首先配置一个IP地址,让IP生效. ifconfig查看当前网络配 ...

  8. Day11 - Python基础11 模块学习——optparse

    Python 有两个内建的模块用于处理命令行参数: 一个是 getopt,<Deep in python>一书中也有提到,只能简单处理 命令行参数: 另一个是 optparse,它功能强大 ...

  9. es6入门7--Set Map数据结构

    本文作为ES6入门第十三章的学习整理笔记,可能会包含少部分个人的理解推测,若想阅读更详细的介绍,还请阅读原文ES6入门 一.set数据结构 1.set不接受重复值 ES6新增了Set构造函数用于创建s ...

  10. 雅礼集训2019 D7T2 Subsequence

    雅礼集训2019 D7T2 Subsequence 直接贴题解: 平衡树代码: #include<bits/stdc++.h> #define ll long long #define N ...