scrapy框架的日志等级和请求传参

Scrapy的日志等级

  

- 在使用scrapy crawl spiderFileName运行程序时,在终端里打印输出的就是scrapy的日志信息。- 日志信息的种类:ERROR : 一般错误WARNING : 警告INFO : 一般的信息DEBUG : 调试信息- 设置日志信息指定输出:在settings.py配置文件中,加入LOG_LEVEL = ‘指定日志信息种类’即可。LOG_FILE = 'log.txt'则表示将日志信息写入到指定文件中进行存储。

请求传参

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

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

爬虫文件:

import scrapy
from moviePro.items import MovieproItemclass 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获取itemitem = 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文件:

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass 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()

管道文件:

# 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.htmlimport 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 itemdef 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

import scrapy
from xiaohua.items import XiaohuaItemclass XiahuaSpider(scrapy.Spider):name = 'xiaohua'allowed_domains = ['www.521609.com']start_urls = ['http://www.521609.com/daxuemeinv/']pageNum = 1url = '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'] = schoolitem['img_url'] = 'http://www.521609.com' + img_urlyield itemif self.pageNum < 10:self.pageNum += 1url = format(self.url % self.pageNum)#print(url)yield scrapy.Request(url=url,callback=self.parse)

 

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

 

# 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.htmlimport json
import os
import urllib.request
class XiaohuaPipeline(object):def __init__(self):self.fp = Nonedef 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 itemdef 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/wanglan/p/10826999.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/569463.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

绝对定位absolute、相对定位relative(脱离文档流)

1、脱离文档流&#xff0c;&#xff1a;父元素高度不再包含文档流高度 position&#xff1a;absolute 子元素 position&#xff1a;relative 父元素&#xff0c; 子元素相对于祖先中的第一个relative定位&#xff0c;用到的 top:0; left:0; 不然出bug 2、相对于屏幕…

第32月第8天 打包 Framework 时使用 CocoaPods 引入第三方库的方法

1. 但是可以发现打包完后的 .framework 包里面是没有 CocoaPods 集成的第三方库的&#xff0c;所以在使用 .framework 包时&#xff0c;工程中必须也要集成 .framework 包中用到的第三方库&#xff0c;否则会找不到文件而报错。 https://www.cnblogs.com/nelsen-chen/p/9353520…

CSS 加过渡效果transition

transition: box-shadow 0.3s; 给按钮加效果 transition: all 0.7s; 给进度条

php后端语言的基本语法

<?php$num 1;//php中定义一个变量echo $num;//php中打印一个值&#xff08;与console。log类似&#xff09;$arr array(1,2,3,4,5,6,7,89);//在php中定义一个数组//echo $arr;php中使用echo不能输出集合&#xff08;数组与对象&#xff09;&#xff0c;//必须采用print_r…

CSS居中问题

1.左浮后&#xff0c;想居中&#xff1a; 给他“爸爸”居中&#xff0c;如果没有宽度&#xff0c;不能用 margin&#xff1a;0 auto;可以用text-align&#xff1a;center&#xff1b; 2.继1&#xff0c;如果“爸爸”也没有确定的宽&#xff0c;想变窄 “爸爸”只能也变成 di…

12-order by和group by 原理和优化 sort by 倒叙

原理和优化 groupBy分组&#xff1f;会造成一个数据倾斜 1.解决方案&#xff1a;将输入在map端进行部分的打乱重分 set hive.groupby.skewindatatrue; 2.在map到reduce端的时候设置combiner进行合并 set hive.map.aggrtrue; 3.在combiner进行合并的时候要知道数据量的大小&…

内联元素(display:inline-block)注意事项

1.内联元素margin的上下没有用&#xff0c;加入 display:inline-block 后&#xff0c;才有用&#xff1b; 不是block块级元素了&#xff0c;那么想居中&#xff0c;用 margin&#xff1a;0 auto; 没用了&#xff0c; 那想居中&#xff0c;在他“父亲”加上 text-align&#x…

多个excel文件内容合并到一个excel文件的多个sheet的小程序

# -*- coding:utf-8 -*-import xlrd, xlsxwriter# 待合并excelallxls ["D:\\excelcs\\***.xlsx"]allxls1 ["D:\\excelcs\\***.xlsx"]allxls2 ["D:\\excelcs\\***.xlsx"]#print(allxls[0:2])# 目标excelend_xls "D:\\excelcs\\***.xlsx&…

【编程训练-考研上机模拟】综合模拟2-2019浙大上机模拟(晴神)

A - next[i] Problem Description 在字符串匹配的KMP算法中有一个重要的概念是next数组&#xff0c;求解它的过程让不少同学伤透了心。next数组的直接语义其实是&#xff1a;使“长度为L的前缀”与“长度为L的后缀”相同的最大L&#xff0c;且满足条件的前后缀不能是原字符串本…

CSS常用工具

wall haven 墙纸 CSS tricks shape 用CSS作图 iconfont.cn 小图标工具网站&#xff0c;&#xff08;添加至项目→symbol→查链接→生成代码→<script>→使用帮助&#xff09; CSS3 linear gradient &#xff08;generator&#xff09; 线性渐变工具 CSS animation…

CSS li 一半左浮一半右浮

.skills >ol li{float: left; 左浮width: 48%;margin-bottom: 40px; } .skills >ol li:nth-child(even){ //even 偶数 odd 奇数float: right; 右浮 }另一种 .skills >ol li:nth-child(1){ //第一个margin-left: 0; }.skills >ol li:first-child{ //…

addEventListener事件委托

什么是事件委托&#xff1a;通俗的讲&#xff0c;事件就是onclick&#xff0c;onmouseover&#xff0c;onmouseout&#xff0c;等就是事件&#xff0c;委托呢&#xff0c;就是让别人来做&#xff0c;这个事件本来是加在某些元素上的&#xff0c;然而你却加到别人身上来做&#…

HTML常遇问题

1、span 里面套 div 会有问题&#xff0c;可以套 span&#xff0c;再加语句 display:block; 相当于套了div 2. 外部不能加padding&#xff0c;所以可以再里层加 div&#xff0c;在加padding可以了 3、display:block; display:inline-block; 让border将它们包住 4、*{ …

bzoj3771:Triple

传送门 生成函数 设生成函数\(f(x)\)&#xff0c;可以将系数定为选的方案数&#xff0c;指数定为代价 那么\[ f(x)\sum_{i1}^{n}x^{w_i} \] 然后答案就是\(f^3(x)f^2(x)f(x)\)然后去掉重复的情况 然后我们设\[ A(x)\sum_{i1}^{n}x^{2w_i}\\ B(x)\sum_{i1}^{n}x^{3w_i} \] 重复的…

CSS图片设置

1、background-position: center center; 图片居中 background-size: cover; 让图片自适应&#xff0c;按比例缩放 2、加背景色mask&#xff0c;面罩&#xff1a; background: rgba(0, 0, 0, 0.7); 宽度不要写&#xff0c;自适应的 3. 图片的宽度&#xff0c;最好先规定好&…

sqlserver——视图

数据库中的视图是一个虚拟表。同真实的表一样&#xff0c;视图包含一系列带有名称的列和行数据&#xff0c;行和列数据用来自由定义视图和查询所引用的表&#xff0c;并且在引用视图时动态产生。本篇将通过一些实例来介绍视图的概念&#xff0c;视图的作用&#xff0c;创建视图…

js常用API

(1) getAttribute 用户写啥是啥&#xff0c;#后面的值&#xff0c;获取用户在上面写的原文&#xff0c;不是浏览器加http协议的东西&#xff1b; <a href"#siteAbout">关于</a> var href a.getAttribute(href) // hrefsiteAbou…

DOM相关(主要是var和let的区别用法)

一、1.节点的类型有七种&#xff0c;分别是&#xff1a;Document&#xff0c;DocumentType&#xff0c;Element&#xff0c;Attribute&#xff0c;Text&#xff0c;Comment&#xff0c;DocumentFragment 2.DOM树的根节点是&#xff1a;html 3.元素Element的NodeType值为&…

JOIN三个表格

表格一 表格二 表格三 SQL语句为 SELECT * FROM movie JOIN casting ON movie.idcasting.movieid     JOIN actor ON casting.actoridactor.id(要注意join 的格式) 最终结果展示在最下面 idtitleyrdirectorbudgetgrossmovieidactoridordidname1001710 Rillington Place19…

深度学习入门|第5章 误差反向传播法(二)

误差反向传播法 前言 此为本人学习《深度学习入门》的学习笔记 四、简单层的实现 本节将用 Python 实现前面的购买苹果的例子。这里&#xff0c;我们把要实现的计算图的乘法节点称为“乘法层”&#xff08;MulLayer&#xff09;&#xff0c;加法节点称为“加法层”&#xff08;…