运行爬虫时,控制台会打印出scrapy
日志信息,我们可以控制scrapy
日志显示等级。
日志等级
我们不管使用何种编程语言编写程序,关于日志基本上我们都是分为4类INFO
/WARNING
/ERROR
/~。我们控制日志等级输出可以在settings.py
中配置
1 2 3 4
| LOG_LEVEL = ‘ERROR’
LOG_FILE = 'log.txt'
|
请求传参
在某些情况下,我们爬取的数据不在同一个页面中,例如,我们爬取一个电影网站,电影的名称,评分在一级页面,而要爬取的其他电影详情在其二级子页面中。这时我们就需要用到请求传参。
我们这里直接通过一个案例来演示如何在请求的时候进行传参。
案例
爬取电影列表页中的电影名称,并获取该电影对应详情页中的电影简介。
爬虫文件
4567tv.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import scrapy from scrapy.http import Request
from scrapyBiography.items import ScrapybiographyItem
class A4567tvtvSpider(scrapy.Spider): name = '4567tvtv' allowed_domains = ['www.4567tv.tv'] start_urls = ['https://www.4567tv.tv/index.php/vod/show/id/5.html']
def parse_info(self, response): desc = response.xpath('//*[@class="detail-sketch"]/text()').extract_first() yield ScrapybiographyItem(tit = response.meta['tit'], desc = desc)
def parse(self, response): videos = response.xpath('//*[@class="stui-vodlist clearfix"]/li/div') for video in videos: video_url = 'https://www.4567tv.tv'+video.xpath('./a/@href').extract_first() video_tit = video.xpath('./a/@title').extract_first() yield Request(url=video_url, callback=self.parse_info, meta={"tit":video_tit})
|
items.py
1 2 3 4 5 6 7 8
| import scrapy
class ScrapybiographyItem(scrapy.Item): # 接收电影标题和简介 tit = scrapy.Field() desc = scrapy.Field()
|
管道文件
pipelines.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class ScrapybiographyPipeline(object): def __init__(self): print('开始爬取') self.f = open('movie.log', 'w+', encoding='utf8') def process_item(self, item, spider): self.f.write('【'+item['tit']+'】-'+item['desc']+'\n') print(item['tit']+' 下载完成……') return item def close_spider(self, spider): self.f.close() print('爬取完成')
|
执行爬虫
电影标题和简介成功写入到了文件中