导览

1. Scrapy install

2. Scrapy 项目创建

3. Scrapy 自定义爬虫类

4. Scrapy 处理逻辑

5. Scrapy 扩展

1. Scrapy install

准备知识

  • pip 包管理
  • Python 安装
  • Xpath
  • Css

Windows安装 Scrapy

$>- pip install scrapy

Linux安装 Scrapy

$>- apt-get install python-scrapy

2. Scrapy 项目创建

在开始爬取之前,必须创建一个新的Scrapy项目。进入自定义的项目目录中,运行下列命令:

$>- scrapy startproject mySpider

其中, mySpider 为项目名称,可以看到将会创建一个 mySpider 文件夹,使用命令查看目录结构

$>- tree mySpider

3. Scrapy 自定义爬虫类

通过Scrapy的Spider基础模版顺便建立一个基础的爬虫。(也可以不用Scrapy命令建立基础爬虫,)

$>- scrapy genspider gzrbSpider dayoo.com

scrapy genspider是一个命令,也是scrapy最常用的几个命令之一。至此,一个最基本的爬虫项目已经建立完毕了.

文件描述:

序列 文件名 描述
1 scrapy.cfg 是整个Scrapy项目的配置文件
2 settings.py 是上层目录中scrapy.cfg定义的设置文件(决定由谁去处理爬取的内容)
3 init.pyc 是__init__.py的字节码文件
4 init.py 作用就是将它的上级目录变成了一个模块 ,否则,文件夹没有__init__.py不能作为模块导入
5 items.py 是定义爬虫最终需要哪些项 (决定爬取哪些项目)
5 pipelines.py Scrapy爬虫爬取了网页中的内容后,这些内容怎么处理就取决于pipelines.py如何设置 (决定爬取后的内容怎样处理)
6 gzrbSpider.py 自定义爬虫类(决定怎么爬)

命令描述:

序列 操作 描述
1 模拟爬广州日报网页 scrapy shell https://www.dayoo.com
2 模拟查看节点数据 response.xpath('.//div[@class="mt35"]//ul[@class="news-list"]').extract()

3 运行爬虫 scrapy crawl gzrbSpider

4. Scrapy 处理逻辑

文件 \spiders\gzrbSpider.py

import scrapy
from mySpider.items import MySpiderItemclass gzrbSpider(scrapy.Spider):name = "gzrbSpider"allowed_domains = ["dayoo.com/"]start_urls = ('https://www.dayoo.com',)def parse(self, response):subSelector = response.xpath('.//div[@class="mt35"]//ul[@class="news-list"]')items = []for sub in subSelector:item = MySpiderItem()item['newName'] = sub.xpath('./li/a/text()').extract()items.append(item)return items

文件 Item.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass MySpiderItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()newName = scrapy.Field()

文件 Setting.py

# Scrapy settings for mySpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.htmlBOT_NAME = 'mySpider'SPIDER_MODULES = ['mySpider.spiders']
NEWSPIDER_MODULE = 'mySpider.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'mySpider(+http://www.yourdomain.com)'# Obey robots.txt rules
ROBOTSTXT_OBEY = True# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
#COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'mySpider.middlewares.mySpiderSpiderMiddleware': 543,
#}# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'mySpider.middlewares.mySpiderDownloaderMiddleware': 543,
#}# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'mySpider.pipelines.mySpiderPipeline': 300,
}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

文件 pipelines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import time# class mySpiderPipeline:
#     def process_item(self, item, spider):
#         return itemclass MySpiderPipeline(object):def process_item(self, item, spider):now = time.strftime('%Y-%m-%d', time.localtime())fileName = 'gzrb' + now + '.txt'for it in item['newName ']:with open(fileName,encoding='utf-8',mode = 'a') as fp:# fp.write(item['newName '][0].encode('utf8') + '\n\n')fp.write(it + '\n\n')return item

本文代码结果展示:

5. Scrapy 扩展

Xpath:

Css:

Python Scrapy 爬虫简单教程相关推荐

  1. Python网络爬虫简单教程——第一部

    Python网络爬虫简单教程--第一部 感谢,如需转载请注明文章出处:https://blog.csdn.net/weixin_44609873/article/details/103384984 P ...

  2. Python Scrapy爬虫框架实战应用

    通过上一节<Python Scrapy爬虫框架详解>的学习,您已经对 Scrapy 框架有了一个初步的认识,比如它的组件构成,配置文件,以及工作流程.本节将通过一个的简单爬虫项目对 Scr ...

  3. scrapy爬虫框架教程(二)-- 爬取豆瓣电影

    前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大家讲解一个完整爬虫的流程. 工具和环境 语言:python 2 ...

  4. Scrapy爬虫入门教程五 Selectors(选择器)

    Scrapy爬虫入门教程一 安装和基本使用 Scrapy爬虫入门教程二 官方提供Demo Scrapy爬虫入门教程三 命令行工具介绍和示例 Scrapy爬虫入门教程四 Spider(爬虫) Scrap ...

  5. python商业爬虫教程_廖雪峰老师的Python商业爬虫课程 Python网络爬虫实战教程 体会不一样的Python爬虫课程...

    廖雪峰老师的Python商业爬虫课程 Python网络爬虫实战教程 体会不一样的Python爬虫课程 1.JPG (53.51 KB, 下载次数: 1) 2019-8-9 08:15 上传 2.JPG ...

  6. python网络爬虫系列教程_Python网络爬虫系列教程连载 ----长期更新中,敬请关注!...

    感谢大家长期对Python爱好者社区的支持,后期Python爱好者社区推出Python网络爬虫系列教程.欢迎大家关注.以下系列教程大纲,欢迎大家补充.视频长期连载更新中 --------------- ...

  7. Python Scrapy 爬虫 - 爬取多级别的页面

    Python Scrapy 爬虫 - 爬取多级别的页面 互联网中众多的 scrapy 教程模板,都是爬取 下一页 → \rightarrow →下一页形式的,很少有 父级 → \rightarrow ...

  8. Python Scrapy 爬虫框架爬取推特信息及数据持久化!整理了我三天!

    最近要做一个国内外新冠疫情的热点信息的收集系统,所以,需要爬取推特上的一些数据,然后做数据分类及情绪分析.作为一名合格的程序员,我们要有「拿来主义精神」,借助别人的轮子来实现自己的项目,而不是从头搭建 ...

  9. python爱心代码简单教程

    python爱心代码简单教程操作方法 1 将以上代码保存为.py文件,假设保存的文件名为 love.py (不会保存?先保存为txt文本,然后将后缀改为.py) 2 在终端(cmd命令窗口)输入pyt ...

最新文章

  1. js form中的onsubmit和action
  2. 小波滤波器与其他滤波器的区别_小波变换(六):小波变换在机器学习中的应用(上)...
  3. vue 常用ui组件
  4. mysql left join 中文_MySQL之LEFT JOIN问题汇总
  5. Flutter进阶—实现动画效果(六)
  6. SAP是如何与外界沟通的?
  7. 内存越界访问保护 内存泄漏研究 未完待续
  8. Tortoise svn 基础知识
  9. 异步IO实现和应用场景
  10. 微信api接口调用-触发推送微信群聊列表
  11. android手机版excel怎样填充序列号,规范日期数据的极简法。Excel填充功能快速填充序号操作详解。如何制作工作日序列号填充,快速填充功能无法使用...
  12. php超链接打不开了,excel超链接无法打开怎么办
  13. 虚拟机挂载ISO文件
  14. 袁永福软件行业从业经历
  15. python绘制中国_使用python绘制中国地图
  16. Beagle填充之坑ERROR: REF field is not a sequence of A, C, T, G, or N characters at
  17. 11微服务认证与授权
  18. Mysql安装-Centos7-阿里云虚拟主机
  19. 王芷蕾、天韵诗班-给我换颗心(心灵不打烊)
  20. DataScience:风控场景之金融评分卡模型的简介、构建(逻辑回归)开发(转评分卡)、使用过程(线上实现)、完整流程之详细攻略

热门文章

  1. Java初级面试题!!自己出几道面试题,感觉很有意思
  2. 多揉人体5大黄金穴养生抗衰老
  3. windows查看进程命令行
  4. 道路排水工程投标施工方案
  5. java会导致蓝屏么,显卡损坏有什么症状,显卡会导致蓝屏吗
  6. 【Arcpy】批量处理遥感图像
  7. scrapy设置headers,cookies
  8. “直男变暖男”—— 当推荐系统遇上知识图谱
  9. Linux(三)远程登录管理工具
  10. python数据分析入门之数据类型(菜鸟学习总结篇)