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. apk系统签名小技巧

    前言 对于经常和android系统打交道的攻城狮来说,给app打系统签名一定是日常操作啦.由于最近使用的比较多,特此总结一下,减少复制粘贴的操作,通过命令行来搞定. 简化前的操作 1.Android ...

  2. 从0系统学Android-2.4 Activity 的生命周期

    本系列文章,参考<第一行代码>,作为个人笔记 更多内容:更多精品文章分类 本系列持续更新中.... 2.4 Activity 的生命周期 掌握 Activity 的生命周期对于开发者来说是 ...

  3. selinux disable

    临时关闭: [root@localhost ~]# getenforceEnforcing [root@localhost ~]# setenforce 0[root@localhost ~]# ge ...

  4. subprocess, re模块,logging, 包等使用方法

    subprocess, re模块,logging, 包等使用方法 subprocess ''' subprocess: sub: 子 process: 进程 可以通过python代码给操作系统终端发送 ...

  5. 初级模拟电路:3-2 BJT的工作原理

    回到目录 和前面介绍二极管的PN结的工作原理一样,BJT的量子级工作机制也非常复杂,一般教科书上为了帮助学习者能快速理解,也都是用一种简化模型的方法来介绍BJT的工作机理,一般只需大致了解即可.只要记 ...

  6. busybox启动流程简单解析:从init到shell login

    关键词:kernel_init().init.inittab.wait/waitpid.fork/vfork.setsid().execvp/execlp.dup2等等. 由于遇到一系列定制,从ini ...

  7. Octave中的一些常用操作

    >> 5+6ans = 11>> 1~=2ans = 1 %1表示true,0表示false>> 1~=1    %1不等于1ans = 0>> a=2 ...

  8. oracle xmltype + blob + clob

    oracle varchar2最大存储长度为4000,所以当字段长度超限时可尝试存储为blob或xmltype格式 xmltype --1.创建xml表 Create TABLE testxml( i ...

  9. 分治 FFT

    为啥要叫分治\(fft\)啊,又用不到\(fft--\) 给定长度为\(n-1\)的数组\(g[1],g[2],--,g[n-1]\),求\(f[1],f[2],--,f[n]\),其中 \[f[i] ...

  10. Codeforces Round #599 (Div. 2) B2. Character Swap (Hard Version) 构造

    B2. Character Swap (Hard Version) This problem is different from the easy version. In this version U ...