第一,scrapy框架的安装

通过命令提示符进行安装(如果没有安装的话)

pip install Scrapy

如果需要卸载的话使用命令为:

pip uninstall Scrapy

第二,scrapy框架的使用

先通过命令提示符创建项目,运行命令:

scrapy startproject crawlquote#crawlquote这是我起的项目名

其次,通过我们的神器PyCharm打开我们的项目--crawlquote(也可以将PyCharm打开我们使用虚拟环境创建的项目)

然后,打开PyCharm的Terminal,如图

然后在命令框中输入

scrapy genspider quotes quotes.toscrape.com

此时的代码目录为:

文件说明:

  • scrapy.cfg  项目的配置信息,主要为Scrapy命令行工具提供一个基础的配置信息。(真正爬虫相关的配置信息在settings.py文件中)

  • items.py    设置数据存储模板,用于结构化数据,如:Django的Model

  • pipelines    数据处理行为,如:一般结构化的数据持久化

  • settings.py 配置文件,如:递归的层数、并发数,延迟下载等

  • spiders      爬虫目录,如:创建文件,编写爬虫规则

quotes.py使我们书写的爬虫---里面是发起请求-->拿到数据---->临时存储到item.py中

运行爬虫命令为:

scrapy crawl quotes

 第三,使用scrapy的基本流程

(1)明确需要爬取的数据有哪些

(2)分析页面结构知道需要爬取的内容在页面中的存在形式

(3)在item.py中定义需要爬取的数据的存储字段

(4)书写爬虫  -spider中定义(spiders中的quotes.py) --数据重新格式化化后在item.py中存储

(5)管道中--pipeline.py ----对item里面的内容在加工 , 以及定义链接数据库的管道

(6)配置文件中----settings.py中开启管道作用:ITEM_PIPELINES ,定义数据库的名称,以及链接地址

(7)中间件中----middlewares.py

根据上述的一个简单的代码演示:

1)item.py中

import scrapy

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

2)spiders--quotes(爬虫)

# -*- coding: utf- -*-
import scrapy
from crawlquote.items import CrawlquoteItem class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/'] def parse(self, response):
quotes = response.css('.quote')
for quote in quotes:
item = CrawlquoteItem()
text = quote.css('.text::text').extract_first() # 获取一个
author = quote.css('.author::text').extract_first()
tags = quote.css('.tags .tag::text').extract()
item['text'] = text
item['author'] = author
item['tags'] = tags
yield item # 将网页中的内容重新生成一个item以便于后面的认识 next = response.css('.pager .next a::attr(href)').extract_first()
url = response.urljoin(next) # urljoin翻页
yield scrapy.Request(url=url, callback=self.parse) # 递归调用

3)pipeline.py中

# -*- coding: utf- -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.exceptions import DropItem class TextPipeline(object):
def __init__(self):
self.limit = def process_item(self, item, spider): # 对重新生成的item进行再制作
if item['text']:
if len(item['text']) > self.limit:
item['text'] = item['text'][:self.limit].rstrip() + '...'
return item
else:
return DropItem('Missing Text') class MongoPipeline(object): # 与数据库有关的操作
def __init__(self, mongo_uri, mongo_db): # () MongoPipeline构造函数
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db @classmethod
def from_crawler(cls, crawler): # ()读取settings里面的值,类方法
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DB')
) def open_spider(self, spider): # ()爬虫启动时需要的操作
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] def process_item(self, item, spider): # 保存到mongodb数据库
name = item.__class__.__name__
self.db[name].insert(dict(item))
return item def close_spider(self, spider): # 关闭mongodb
self.client.close()

4)settings.py中

BOT_NAME = 'crawlquote'

SPIDER_MODULES = ['crawlquote.spiders']
NEWSPIDER_MODULE = 'crawlquote.spiders' #数据库链接
MONGO_URI = 'localhost'
MONGO_DB = 'crawlquote' #项目管道开启
ITEM_PIPELINES = {
'crawlquote.pipelines.TextPipeline': ,
'crawlquote.pipelines.MongoPipeline': ,
}

5)此处还没有用的middelwares.py

总结一下:

针对某部分数据的爬取,先要在item中定义字段,然后在爬虫程序中通过选择器拿到数据并存储到item中,再然后通过pipeline的在加工+setting文件修改--存储到数据库中。此时简单爬取就实现了。

最新文章

  1. ajax处理缓冲问题
  2. 实战:rsync+inotify实现数据实时同步
  3. poj 2063 Investmen 完全背包
  4. OrmLite数据库的使用方法
  5. Bugtags 2016-06-16 更新内容
  6. PTA List Components
  7. nginx的特点
  8. 2cifang.com_2次方学习
  9. Spark里面:获取图Spark有多少行代码
  10. java中的反射机制_____
  11. Dubbo负载均衡策略
  12. 发布内网网站服务器让公网可以访问,无需NAT
  13. Java进阶篇设计模式之三 ----- 建造者模式和原型模式
  14. 五十四、linux 编程——TCP 编程模型
  15. Coursera, Deep Learning 1, Neural Networks and Deep Learning - week4, Deep Neural Networks
  16. TensorFlow at Google I/O 2018
  17. Python学习笔记之--我又开始学习Python了(随时更新)
  18. SpringBoot使用Spring Initializer
  19. [Javascript] Hositing
  20. HDU 2048 错排

热门文章

  1. 在web.xml中配置spring配置文件的路径
  2. QT Designer 的汉化
  3. uboot配置过程详解1
  4. MongoDB 高可用集群架构简介
  5. spring import jar中的bean配置文件
  6. 守护进程vs 守护线程
  7. (五)java进制
  8. 运用 jenkins 让你的项目优雅的持续化集成
  9. spring源码学习之:springAOP实现底层原理
  10. javascript的八张思维导图