scrapy框架
-
什么是框架
- 就是一个集成了很多功能并且具有很强通用性的一个项目模板。
-
如何学习框架
- 专门学习框架封装的各种功能的详细用法。
-
什么是scrapy
- 爬虫中封装好的一个明星框架。
- 功能介绍;
- 高性能的持久化存储
- 异步的数据下载
- 高性能的数据解析操作
- 分布式
……
-
scrapy框架的基本使用
-
环境安装:
- mca or linux:pip install scrapy
- windows:
- pip install wheel
- twisted下载地址
- pywin32下载地址
- scrapy下载地址
- pip install twisted
- pip install pywin32
- pip install scrapy
测试:在终端输入scrapy指令,未报错即表示安装成功。
-
创建一个工程:scrapy startproject firstBlood
-
cd firstBlood
-
需要在spiders子目录中创建一个爬虫文件
- scrapy genspider spiderName www.xxx.com
-
执行工程:
- scrapy crawl spiderName
-
settings.py设置:
- LOG_LEVEL = ‘ERROR’ 表示工程执行只输出错误的日志
- ROBOTSTXT_OBEY = False 表示不遵守robots协议
- UA伪装
-
-
scrapy数据解析
-
scrapy持久化存储
- 基于终端指令:
- 要求:只可以将parse方法的返回值存储到本地
- 注意:持久化存储对应的文本文件的类型只可以为:json,jsonlines,jl,csv,xml
- scrapy crawl life -o ./path
- 好处:简洁高效便捷
- 缺点:局限性较强(数据只能存储到指定后缀的文件中)
- 基于管道:
- 编码流程:
- 数据解析
- 编码流程:
- 基于终端指令:
import scrapy
from lifePro.items import LifeproItem
class LifeSpider(scrapy.Spider):
name = 'life'
# allowed_domains = ['https://www.qiushibaike.com/text/']
start_urls = ['https://www.qiushibaike.com/text/']
def parse(self, response):
# 解析:作者的名称和段子的内容
div_list = response.xpath('//div[@class="col1 old-style-col1"]/div')
# 存储所有解析到的数据
# all_data = []
for div in div_list:
# extrac可以将selector对象中data参数存储的字符串提取出来
# author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
author = div.xpath(
'./div[1]/a[2]/h2/text() | ./div[1]/span/h2/text()').extract_first()
content = div.xpath('./a[1]/div//span/text()').extract()
content = ''.join(content)
# 将数据封装存储到item对象中
item = LifeproItem()
item['author'] = author
item['content'] = content
# 将item提交给管道
yield item
# 终端持久化存储
# dic = {
# 'author':author,
# 'content':content
# }
# all_data.append(dic)
# return all_data
# print('作者:', author, content)
- 在item类中定义相关的属性
import scrapy
class LifeproItem(scrapy.Item):
# define the fields for your item here like:
author = scrapy.Field()
content = scrapy.Field()
# pass
- 将解析的数据封装存储到item类型的对象中
- 将item类型的对象提交给管道进行持久化存储的操作
- 在管道类的process_item中要将其接收到的item对象中存储的数据进行持久化存储操作
from itemadapter import ItemAdapter
class LifeproPipeline:
fp = None
# 重写父类的一个方法:该方法只在开始爬虫的时候被调用一次
def open_spider(self,spider):
print('开始爬取')
self.fp = open('./lifePro/spiders/data/life.txt','w',encoding='utf-8')
def process_item(self, item, spider):
author = item['author']
content = item['content']
self.fp.write(author+':'+content+'\n')
return item
def close_spider(self,spider):
print('爬取完毕')
self.fp.close()
- 在配置文件中开启管道
ITEM_PIPELINES = {
'lifePro.pipelines.LifeproPipeline': 300,
}