日志等級
日志等級(種類): ERROR:錯誤 WARNING:警告 INFO:一般信息 DEBUG:調試信息(默認) 指定輸入某一中日志信息: settings:LOG_LEVEL = ‘ERROR’ 將日志信息存儲到制定文件中,而並非顯示在終端里: settings:LOG_FILE = ‘log.txt’ 請求傳參:爬取的數據值不在同一個頁面中。 需求:將id97電影網站中電影詳情數據進行爬取(名稱,類型,導演,語言,片長)
如何讓終端顯示錯誤信息
在settings.py中配置
# 指定終端輸入指定種類日志信息 LOG_LEVEL = 'ERROR' # 存儲到文件 LOG_FILE = 'log.txt'
請求傳參
請求傳參:爬取的數據值不在同一個頁面中。
(id97電影網站)
在電影網站
中電影詳情數據進行爬取(名稱,類型,導演,語言,片長)
創建moviePro工程
scrapy startproject moviePro
cd moviePro
scrapy genspider movie www.id97.com
電影名稱和類型在一頁
電影的其他詳情在另外一頁
爬蟲文件movie.py

import scrapy from moviePro.items import MovieproItem class MovieSpider(scrapy.Spider): name = 'movie' #allowed_domains = ['www.id97.com'] start_urls = ['https://www.55xia.com/movie'] print(' start_urls') # 用於解析二級頁面數據 def parseBySecondPage(self,response): # 直接復制網頁端的xpath director = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[1]/span/text()').extract_first() language = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[6]/td[2]/text()').extract_first() longTime = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[8]/td[2]/text()').extract_first() # 取出Request方法的meta參數傳遞過來的字典(response.meta) item = response.meta['item'] item['director'] = director item['language'] = language item['longTime'] = longTime # 將item提交給管道 print('將item提交給管道') yield item def parse(self, response): # 需求:將id97電影網站中電影詳情數據進行爬取(名稱,類型,導演,語言,片長) div_list = response.xpath('/html/body/div[1]/div[1]/div[2]/div') for div in div_list: # extract_first()第一個 name = div.xpath(".//div[@class='meta']/h1/a/text()").extract_first() kind = div.xpath('.//div[@class="otherinfo"]//text()').extract() # 將kind列表轉化成字符串 kind = " ".join(kind) url = div.xpath('.//div[@class="meta"]/h1/a/@href').extract_first() # href="//www.55xia.com/movie/638284.html url = 'https:'+url # 創建items對象 item = MovieproItem() item['name'] = name item['kind'] = kind item['url'] = url print('創建items對象') # 需要對url發起請求,獲取頁面數據,進行指定數據解析 # 問題:如何將剩下的電影詳情數據存儲到item對象(meta) # 需要對url發起請求,獲取頁面數據,進行指定數據解析 # meta參數只可以賦值一個字典(將item對象先封裝到字典) yield scrapy.Request(url=url, callback=self.parseBySecondPage, meta={'item': item})
items.py
import scrapy class MovieproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field() kind = scrapy.Field() director = scrapy.Field() language = scrapy.Field() longTime = scrapy.Field() url = scrapy.Field()
管道pipelines.py
class MovieproPipeline(object): fp = None def open_spider(self, spider): self.fp = open('movie.txt', 'w', encoding='utf-8') def process_item(self, item, spider): print('------process_item-------') detail = item['name'] + ':' + item['kind'] + ':' + item['director'] + ':' + item['language'] + ':' + item[ 'longTime'] + '\n\n\n' self.fp.write(detail) return item def close_spider(self, spider): self.fp.close()