【Python】Scrapy完成電影信息爬取並存入數據庫

本文使用了scrapy框架對電影信息進行爬取並將這些數據存入MySQL數據庫。

一、安裝相關python模塊

根據你所使用的python包管理器安裝相應的模塊。比如使用pip:

pip install scrapy
pip install pymysql

二、創建scrapy項目

和其他python框架一樣,利用scrapy startproject projectname命令創建項目即可:
在這裏插入圖片描述
出現上圖提示即說明scrapy項目創建成功,如果出現command not found等提示,說明你需要重新安裝scrapy。項目創建成功後的項目目錄如圖所示:
在這裏插入圖片描述
這裏介紹一下部分文件的主要作用。

  1. items.py文件裏主要存放你的模型,即實體。
  2. pipelines.py爬蟲抓取到網頁數據後在該文件中執行相關數據處理操作。
  3. settings.py存放框架配置。
  4. spiders/該文件夾下放爬蟲業務代碼。

三、coding

  1. items.py,我們需要分析我們爬取的信息。
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy

class DialogItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

class Movie(scrapy.Item):
	name = scrapy.Field()           #電影名稱
	href = scrapy.Field()			#電影鏈接
	actor = scrapy.Field()			#演員
	status = scrapy.Field()			#狀態
	district = scrapy.Field()		#地區
	director = scrapy.Field()		#導演
	genre = scrapy.Field()			#類型
	intro = scrapy.Field()			#介紹
  1. 在Spider文件夾下創建爬蟲文件MovieSpider.py,創建MovieSpider類時並繼承scrapy.Spider。這裏使用了xpath定位資源,下面會簡單介紹,更多用法請點擊這裏,進入菜鳥教程進行學習。
import scrapy
from movie.items import Movie

class MovieSpider(scrapy.Spider):
	# 爬蟲名稱,最終會利用該名稱啓動爬蟲
	name = 'MovieSpider'
	# 這裏只填寫域名即可,不需要協議和資源地址
	allowed_domains = ['88ys.com']
	# 開始url,即我們爬蟲最開始需要爬取的地址
	start_urls = ['https://www.88ys.com/vod-type-id-14-pg-1.html']

	def parse(self, response):
		urls = response.xpath('//li[@class="p1 m1"]')
		for item in urls:
			movie = Movie()
			movie['name'] = item.xpath('./a/span[@class="lzbz"]/p[@class="name"]/text()').extract_first()
			movie['href'] = 'https://www.88ys.com' + item.xpath('./a/@href').extract_first()
			request = scrapy.Request(movie['href'], callback=self.crawl_details)
			request.meta['movie'] = movie
			yield request

	def crawl_details(self, response):
		movie = response.meta['movie']
		movie['actor'] = response.xpath('//div[@class="ct-c"]/dl/dt[2]/text()').extract_first()
		movie['status'] = response.xpath('//div[@class="ct-c"]/dl/dt[1]/text()').extract_first()
		movie['district'] = response.xpath('//div[@class="ct-c"]/dl/dd[4]/text()').extract_first()
		movie['director'] = response.xpath('//div[@class="ct-c"]/dl/dd[3]/text()').extract_first()
		movie['genre'] = response.xpath('//div[@class="ct-c"]/dl/dd[1]/text()').extract_first()
		movie['intro'] = response.xpath('//div[@class="ee"]/text()').extract_first()
		yield movie

xpath使用

syntax 說明
// 全文遞歸搜索
. 選取當前結點
. . 選取父節點
text() 選取標籤下的文本
@屬性 選取該屬性的值
label 這裏指節點名稱,即html的標籤
div[@class="ct-c"] 指類屬性爲ct-c的div
/dl/dt[1] 指dl下的第一個dt
  1. 編寫pipelines.py,將爬取到的數據存入數據庫
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import pymysql


class DialogPipeline(object):
    def __init__(self):
        self.conn = pymysql.connect('localhost', 'huangwei', '123456789', 'db_88ys')
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        sql = "insert into tb_movie(name, href, actor, status, district, director, genre, intro) values(%s, %s, %s, %s, %s, %s, %s, %s)"
        self.cursor.execute(sql, (item['name'], item['href'], item['actor'], item['status'],
            item['district'], item['director'], item['genre'], item['intro']) )
        self.conn.commit()

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()
  1. 更改settings.py相關配置
# 是否遵循robots協議
ROBOTSTXT_OBEY = False

# 模擬瀏覽器進行數據請求
DEFAULT_REQUEST_HEADERS = {
    "User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;",
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}

# 啓用pipelines,將爬取到的數據進行保存
ITEM_PIPELINES = {
   'dialog.pipelines.DialogPipeline': 300,
}

四、啓動爬蟲

進入項目目錄,使用scrapy crawl MovieSpider即可,執行中會打印相關日誌,在命令中加入--nolog即可不顯示日誌。當然,在啓動前我們需要準備好數據表。啓動過程如下:
在這裏插入圖片描述
最終,我們查看數據庫,爬取成功!!!
在這裏插入圖片描述

發佈了73 篇原創文章 · 獲贊 282 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章