Scrapy介绍
----------------------------SCRAPY介绍----------------------------------------
什么是Scrapy Scrapy
- 是⼀个为了爬取⽹站数据,提取结构性数据⽽编写的应⽤框架,我们只 需要实现少量的代码,就能够快速的抓取
- Scrapy使⽤了Twisted异步⽹络框架,可以加快我们的下载速度
- 可配置和扩展性高
- 框架是基于异步Twisted异步网络框架,扭曲的
scrapy网址介绍:
- http://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/overview.html
异步和⾮阻塞的区别
- 同步:调用在发出之后,这个调用等待上一个调用执行结束之后,在返回。
- 异步:调⽤在发出之后,这个调⽤就直接返回,不管有⽆结果
- ⾮阻塞:关注的是程序在等待调⽤结果时的状态,指在不能⽴刻得到结果之 前,该调⽤不会阻塞当前线程
Scrapy 工作流程
- 1 引擎 整个框架的核心
- 2 调度器 接收从引擎发过来的url,并入列
- 3 下载器 下载网页源码,返回给爬虫程序
- 4 项目管理 数据处理
- 5 下载中间件 处理引擎与下载器之间的请求
- 6 爬虫中间件 处理爬虫程序响应和输出结果以及新的请求
。下载中间件和爬虫中间件是负责引擎和下载器还有引擎和爬虫程序之间的数据传输。

scrapy工作流程


工作原理图
scrapy入门
-------------创建scrapy以及爬虫----------------------------------------------
- 创建scrapy项目
- 第一步创建Scrapy项目
scrapy startproject mySpider- 第二步创建爬虫项目
cd mySpider
scrapy genspider example example.com example 爬虫程序的名字example.com 爬取的网站的域名(范围)
- 在命令行中运行爬虫
scrapy crawl qb # qb爬⾍的名字
- 在pycham中运行爬虫
from scrapy import cmdline
cmdline.execute(“scrapy crawl qb”.split())
------------------scrapy设置---------------------------------------------------
- settings文件设置
是否遵守robots协议 一般给为False
ROBOTSTXT_OBEY = False ##爬虫与网站的一个协议,什么可以爬,什么不可以爬 建议改为false
最大并发量 默认是16
Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 32
下载延迟为3秒
DOWNLOAD_DELAY = 3
LOG_LEVEL=‘WARNING’ #过滤一些报错日志
#请求报头 在这里需要添加请求报头
DEFAULT_REQUEST_HEADERS = {
‘User-Agent’:‘Mozilla/5.0’,
‘Accept’:
‘text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8’,
‘Accept-Language’: ‘en’,
}
爬虫中间件
SPIDER_MIDDLEWARES = {
‘mySpider.middlewares.MyspiderSpiderMiddleware’: 543,
}
下载中间件
DOWNLOADER_MIDDLEWARES = {
‘mySpider.middlewares.MyspiderDownloaderMiddleware’: 543,
}
管道
ITEM_PIPELINES = {
‘mySpider.pipelines.MyspiderPipeline’: 300,
}
案例
- 在豆瓣网页中拿到属性栏的名称
。直接拿到response数据 解析这个数据
。通过分析它里面有 xpath css等方法 - 注意
item = {}
li_list = response.xpath(’//div[@class=“side-links navanon”]/ul/li’)
for li in li_list:
item[‘name’] = li.xpath(‘a/em/text()’).extract_first()
if item[‘name’] == None:
item[‘name’] = li.xpath(‘a/text()’).extract_first()
print(item)
在这个selector对象中有这么几个方法
旧方法
extract_first() 显示第一条数据
extract 显示多条数据
新方法
get() 显示第一条数据
getall()显示多条数据
-----------------------------------代码-------------------------------------------------------
--------------爬虫模块
import scrapy
#from scrapy.http.response.html import HtmlRespons
#from 爬虫.Day18 import MyspiderItem
from 爬虫.Day18.scarpy框架.mySpider.mySpider.settings import MYSQL_HOST
class DbSpider(scrapy.Spider):
name = 'db'
allowed_domains = ['douban.com'] #可以修改
start_urls = ['http://douban.com/'] #开始的url 可以修改的
def parse(self, response):
# print('*'*80)
# print(response)
# print(type(response))
# print('*' * 80)
'''
在path方法当中 在Scrapy 中为我们封装了一些方法 xpath css 在selector对象中
在这个selector对象中有这么几个方法
旧方法
extract_first() 显示第一天数据
extract 显示多条数据
新方法
get() 显示第一条数据
getall() 显示多条数据
'''
item={} #dict
#item=MyspiderItem() # MyspiderItem对象
li_list=response.xpath('//div[@class="side-links nav-anon"]/ul/li')
for li in li_list:
item['title']=li.xpath('a/em/text()').extract_first()
if item['title']==None:
item['title'] = li.xpath('a/text()').extract_first()
#item['db_host']=MYSQL_HOST
#另一种方式
#item['db_host']=self.settings.get('MYSQL_HOST')
#print(item)
#return item #在scrapy中把数据给管道用的是yield关键字 不是return
#item['title']='db'
yield item
---------
----设置模块—(settings)--------------
---------
# 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.html
#Scrapy 项目名
BOT_NAME = 'mySpider'
MYSQL_HOST='127.0.0.1'
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
#是否遵守robots协议 一般改为False
ROBOTSTXT_OBEY = False #爬虫与网站的一个协议,什么可以爬,什么不可以爬 建议改为false
LOG_LEVEL='WARNING' #过滤一些报错日志
#最大并发量 默认为16
# Configure maximum concurrent requests performed by Scrapy (default: 16) #设置最大的并发量 默认为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
#下载延迟为3秒
#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 = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'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,#这个值越小表示先执行
#'mySpider.pipelines.MyspiderPipeline1': 400 #这个数字就是一个权重(权重越大,就先执行)
}
# 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'
--------
--------管道(piplines)-------------
--------
# 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 json
from 爬虫.Day18.scarpy框架.mySpider.mySpider.settings import MYSQL_HOST
class MyspiderPipeline:
# def __init__(self):
# self.f=open('demo.json','w',encoding='utf-8')
#
# def open_spider(self,item):#爬虫开始的方法 open_spider(self)方法名固定,不能够写错(名字不能变)
# print('爬虫开始了')
def process_item(self, item, spider):
#item['hello']='world'
#print(item)
# item_json=json.dumps(item,ensure_ascii=False)#加ensure_ascii=False 否则默认使用的是asc2,文件会出现乱码
# self.f.write(item_json + '\n')
#print(spider.name)#爬虫名称
#print(type(spider))
#print(item['come_from'])
#item['pip_host']=MYSQL_HOST
#另一种方式
item['pip_host']=spider.settings.get('MYSQL_HOST')
print(item)
return item
# def close_spider(self,item): #爬虫结束的方法 item位置参数 close_spider(self,item)方法名固定,不能够写错
# print('爬虫结束了')
# self.f.close()
class MyspiderPipeline1:
def prcess_item(self,item,spider):#spider是一个对象 item本身拿来的一个值
print("-"*10)
#print(item)
return item
Scrapy是一个用于爬取网站数据的Python框架,基于异步的Twisted框架,提供高效的数据提取。其工作流程包括引擎、调度器、下载器、爬虫中间件和下载中间件等组件。在Scrapy中,可以通过设置文件调整如并发量、下载延迟等参数。项目创建和运行简单,只需几步即可启动爬虫。此外,Scrapy还支持自定义爬虫中间件和数据处理管道,方便进行数据清洗和存储。在实际应用中,可通过XPath或CSS选择器解析网页内容,获取所需数据。



5054

被折叠的 条评论
为什么被折叠?



