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. centOS极简安装并启动ngnix

    我在网上看到过很多种方法在centOS中安装nginx,比如像这样的: 这种方式太麻烦了,看了很恶心. 我在官网看到有这样一种操作,可谓极简.特此记录一下:(官网教程地址:http://nginx.o ...

  2. Redis 找出大 key

    系统: CentOS 7.4 64bit yum install python-pip gcc gcc-c++ python-devel git tmux -y pip install rdbtool ...

  3. Linux—vi/vim命令详解

    如何在 vi 里搜索关键字 在命令模式下敲斜杆( / )这时在状态栏(也就是屏幕左下脚)就出现了 "/" 然后输入你要查找的关键字敲回车就行了. 如果你要继续查找此关键字,敲字符 ...

  4. xshell连接console口

  5. java8-13-默认方法 静态方法 重复注解 类型注解

    java8增加默认方法 静态方法   重复注解 类型注解   1.默认方法 default修饰   为什么要有这个特性? 当修改接口时候,需要修改全部实现该接口的类.为了解决这个问题,所以引进默认方法 ...

  6. 设计模式-Bridge(结构型模式)-用于客户需求较多,频繁对类进行添加修改的情形,将抽象类与具体实现类分开

    以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码 //AbstractionImp.h #pragma once class AbstractionImp { public: ...

  7. WPF 精修篇 用户控件

    原文:WPF 精修篇 用户控件 增加用户控件 数据绑定还是用依赖属性 使用的事件 就委托注册一下 public delegate void ButtonClick(object b,EventArgs ...

  8. Spring Cloud Zuul 那些你不知道的功能点

    本文摘自于 <Spring Cloud微服务 入门 实战与进阶> 一书. 1. /routes 端点 当@EnableZuulProxy与Spring Boot Actuator配合使用时 ...

  9. Mac下vim安装taglist

    1 安装taglist taglist 的安装非常简单.从vim官网的这个链接 http://www.vim.org/scripts/script.php?script_id=273,就可以下载到ta ...

  10. mysql中的replace

    replace字面意思是替换,在mysql里面的运用是 如下图所示 1.  replace into test values(6, 'wowowo', 'new', 'japan') 这条语句则他会正 ...