一.Scrapy的日志等级

  - 在使用scrapy crawl spiderFileName运行程序时,在终端里打印输出的就是scrapy的日志信息。

  - 日志信息的种类:

        ERROR : 一般错误

        WARNING : 警告

        INFO : 一般的信息

        DEBUG : 调试信息

       

  - 设置日志信息指定输出:

    在settings.py配置文件中,加入

LOG_LEVEL = ‘指定日志信息种类’即可。

LOG_FILE = 'log.txt'则表示将日志信息写入到指定文件中进行存储。

二.请求传参

  - 在某些情况下,我们爬取的数据不在同一个页面中,例如,我们爬取一个电影网站,电影的名称,评分在一级页面,而要爬取的其他电影详情在其二级子页面中。这时我们就需要用到请求传参。

  - 案例展示:爬取www.id97.com电影网,将一级页面中的电影名称,类型,评分一级二级页面中的上映时间,导演,片长进行爬取。

  爬虫文件:

# -*- coding: utf-8 -*-
import scrapy
from moviePro.items import MovieproItem class MovieSpider(scrapy.Spider): name = 'movie' allowed_domains = ['www.id97.com'] start_urls = ['http://www.id97.com/'] def parse(self, response): div_list = response.xpath('//div[@class="col-xs-1-5 movie-item"]') for div in div_list: item = MovieproItem() item['name'] = div.xpath('.//h1/a/text()').extract_first() item['score'] = div.xpath('.//h1/em/text()').extract_first() #xpath(string(.))表示提取当前节点下所有子节点中的数据值(.)表示当前节点 item['kind'] = div.xpath('.//div[@class="otherinfo"]').xpath('string(.)').extract_first() item['detail_url'] = div.xpath('./div/a/@href').extract_first() #请求二级详情页面,解析二级页面中的相应内容,通过meta参数进行Request的数据传递 yield scrapy.Request(url=item['detail_url'],callback=self.parse_detail,meta={'item':item}) def parse_detail(self,response): #通过response获取item item = response.meta['item'] item['actor'] = response.xpath('//div[@class="row"]//table/tr[1]/a/text()').extract_first() item['time'] = response.xpath('//div[@class="row"]//table/tr[7]/td[2]/text()').extract_first() item['long'] = response.xpath('//div[@class="row"]//table/tr[8]/td[2]/text()').extract_first() #提交item到管道 yield item

  items文件:

# -*- coding: utf-8 -*-# Define here the models for your scraped items
# # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class MovieproItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() score = scrapy.Field() time = scrapy.Field() long = scrapy.Field() actor = scrapy.Field() kind = scrapy.Field() detail_url = scrapy.Field()

管道文件:

# -*- 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 MovieproPipeline(object): def __init__(self): self.fp = open('data.txt','w') def process_item(self, item, spider): dic = dict(item) print(dic) json.dump(dic,self.fp,ensure_ascii=False) return item def close_spider(self,spider): self.fp.close()

三.如何提高scrapy的爬取效率

增加并发:默认scrapy开启的并发线程为32个,可以适当进行增加。在settings配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置成了为100。降低日志级别:在运行scrapy时,会有大量日志信息的输出,为了减少CPU的使用率。可以设置log输出信息为INFO或者ERROR即可。在配置文件中编写:LOG_LEVEL = ‘INFO’ 禁止cookie: 如果不是真的需要cookie,则在scrapy爬取数据时可以进制cookie从而减少CPU的使用率,提升爬取效率。在配置文件中编写:COOKIES_ENABLED = False 禁止重试: 对失败的HTTP进行重新请求(重试)会减慢爬取速度,因此可以禁止重试。在配置文件中编写:RETRY_ENABLED = False 减少下载超时: 如果对一个非常慢的链接进行爬取,减少下载超时可以能让卡住的链接快速被放弃,从而提升效率。在配置文件中进行编写:DOWNLOAD_TIMEOUT = 10 超时时间为10s 

测试案例:爬取校花网校花图片 www.521609.com

# -*- coding: utf-8 -*-
import scrapy
from xiaohua.items import XiaohuaItem class XiahuaSpider(scrapy.Spider): name = 'xiaohua' allowed_domains = ['www.521609.com'] start_urls = ['http://www.521609.com/daxuemeinv/'] pageNum = 1 url = 'http://www.521609.com/daxuemeinv/list8%d.html' def parse(self, response): li_list = response.xpath('//div[@class="index_img list_center"]/ul/li') for li in li_list: school = li.xpath('./a/img/@alt').extract_first() img_url = li.xpath('./a/img/@src').extract_first() item = XiaohuaItem() item['school'] = school item['img_url'] = 'http://www.521609.com' + img_url yield item if self.pageNum < 10: self.pageNum += 1 url = format(self.url % self.pageNum) #print(url) yield scrapy.Request(url=url,callback=self.parse) 

# -*- coding: utf-8 -*-# Define here the models for your scraped items
# # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class XiaohuaItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() school=scrapy.Field() img_url=scrapy.Field() 

# -*- 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 import os import urllib.request class XiaohuaPipeline(object): def __init__(self): self.fp = None def open_spider(self,spider): print('开始爬虫') self.fp = open('./xiaohua.txt','w') def download_img(self,item): url = item['img_url'] fileName = item['school']+'.jpg' if not os.path.exists('./xiaohualib'): os.mkdir('./xiaohualib') filepath = os.path.join('./xiaohualib',fileName) urllib.request.urlretrieve(url,filepath) print(fileName+"下载成功") def process_item(self, item, spider): obj = dict(item) json_str = json.dumps(obj,ensure_ascii=False) self.fp.write(json_str+'\n') #下载图片 self.download_img(item) return item def close_spider(self,spider): print('结束爬虫') self.fp.close() 

配置文件:

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'# Obey robots.txt rules
ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) CONCURRENT_REQUESTS = 100 COOKIES_ENABLED = False LOG_LEVEL = 'ERROR' RETRY_ENABLED = False DOWNLOAD_TIMEOUT = 3 # Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 DOWNLOAD_DELAY = 3

转载于:https://www.cnblogs.com/marry215464/p/10477182.html

scrapy two相关推荐

  1. Python 爬虫框架Scrapy安装汇总

    传统方式安装Scrapy(慎用) 练习了基本的操作之后,当然就要找框架来进行爬虫实验啊.于是就在网上找Windows 64安装Scrapy的方法,查到的都是非常繁琐的安装方式,由于Scrapy有很多个 ...

  2. Python:爬虫框架Scrapy的安装与基本使用

    一.简单实例,了解基本. 1.安装Scrapy框架 这里如果直接pip3 install scrapy可能会出错. 所以你可以先安装lxml:pip3 install lxml(已安装请忽略). 安装 ...

  3. Python:Scrapy实战项目手机App抓包爬虫

    1. items.py class DouyuspiderItem(scrapy.Item):name = scrapy.Field()# 存储照片的名字imagesUrls = scrapy.Fie ...

  4. Python:Scrapy的settings

    Settings Scrapy设置(settings)提供了定制Scrapy组件的方法.可以控制包括核心(core),插件(extension),pipeline及spider组件.比如 设置Json ...

  5. Python:Scrapy Shell

    Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据. 如果安装了 IPyth ...

  6. Python:Scrapy的安装和入门案例

    Scrapy的安装介绍 Scrapy框架官方网址:http://doc.scrapy.org/en/latest Scrapy中文维护站点:http://scrapy-chs.readthedocs. ...

  7. Python:Scrapy 框架简单介绍

    Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非 ...

  8. python爬虫之Scrapy框架的post请求和核心组件的工作 流程

    python爬虫之Scrapy框架的post请求和核心组件的工作 流程 一 Scrapy的post请求的实现 在爬虫文件中的爬虫类继承了Spider父类中的start_urls,该方法就可以对star ...

  9. 『Scrapy』爬虫框架入门

    框架结构 引擎:处于中央位置协调工作的模块 spiders:生成需求url直接处理响应的单元 调度器:生成url队列(包括去重等) 下载器:直接和互联网打交道的单元 管道:持久化存储的单元 框架安装 ...

  10. python3 scrapy中文文档_Scrapy官方文档笔记

    1.创建Scrapy项目 首先用cmd命令行去操作,输入 scrapy startproject 项目名 #这里输入的项目名,就是在你输入的目录它会建立一个新的文件夹,这个文件夹里面还是同样名字的一个 ...

最新文章

  1. VB 6.0中如何访问EXCEL 2007及EXCEL 2010
  2. android studio编译提示错误:android Error:(21, 19) 错误: 程序包R不存在
  3. ubuntu安装WPS
  4. splitter 使用
  5. 越绿自己,就会越强?
  6. java8 supplyasync_java – 为什么CompletableFuture.supplyAsync成功随...
  7. winrar注册码激活码
  8. android金逸电影院客户端
  9. 使用NSSM配置守护进程 Nginx(Windows)
  10. 从虚拟偶像到“网红”VUP,变现狂欢下的浮士德交易
  11. 汉语言文学如何利用计算机思维,计算机在应用于汉语言文学时产生的优势与局限.PDF...
  12. RFID 工作频率的分类
  13. java学习之道 --- 如何学习java?
  14. win10重装系统后连不上公司服务器,win10重装系统后连不上网有什么解决方法
  15. 正版软件汇集,遥感集市
  16. 项目管理工作中的一些自我反省
  17. 程序员用技术在「抖音」上「撩妹」
  18. AD18添加LOGO图标更改大小
  19. php cms 2017 排名,cms系统排行_PHP CMS系统排行榜
  20. TL-WDN5200H无线usb网卡在Linux上的使用

热门文章

  1. AI和大数据下,前端技术将如何发展?
  2. 知识图谱数据构建的“硬骨头”,阿里工程师如何拿下?
  3. pytorch 三维点分类_三维点云分类与分割-PointNet
  4. 朱峰谈概念设计(七)创作性绘画教程
  5. 《铲子骑士》:“复古游戏”的集大成者
  6. STEAM 97%好评,体验堪比《杀戮尖塔》,为什么玩家说这是2020年上半年最超值的游戏?
  7. 百思不得其解,一个钻石玩家可以短时间上王者?因为猎游?
  8. SQL基础【十一、分页 limit top rownum】
  9. linux OOM-killer机制(杀掉进程,释放内存)
  10. Oracle 11g新特性:Result Cache