在創(chuàng)建新的scrapy爬蟲之前纽甘,我們需要先了解一下創(chuàng)建一個(gè)scrapy爬蟲的基本步驟
一玖雁、確定要爬取的數(shù)據(jù)
以爬取豆瓣電影數(shù)據(jù)為例:
每部電影所要爬取的信息有:
- 片名:《頭號(hào)玩家》
- 導(dǎo)演: 史蒂文·斯皮爾伯格
- 編劇: 扎克·佩恩 / 恩斯特·克萊恩
- 主演: 泰伊·謝里丹 / 奧利維亞·庫(kù)克 / 本·門德爾森 / 馬克·里朗斯 / 麗娜·維特 / 更多...
- 類型: 動(dòng)作 / 科幻 / 冒險(xiǎn)
所以items文件的代碼如下:
#items.py
import scrapy
class DoubanItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
movie_name = scrapy.Field()
movie_dir = scrapy.Field()
movie_editors = scrapy.Field()
movie_actors = scrapy.Field()
movie_type = scrapy.Field()
二、爬取所需的信息
確定了要爬取的信息后,就可以開始寫爬蟲的代碼了。
首先彼棍,我們創(chuàng)建一個(gè)爬蟲文件已添。
在命令行中輸入如下命令(必須在爬蟲項(xiàng)目的文件夾里):
scrapy genspider spidername "domain"
#spidername是要?jiǎng)?chuàng)建的爬蟲的名字,必須是唯一的滥酥,而且不能和爬蟲項(xiàng)目名相同
#domain是要爬取的網(wǎng)站的 host更舞,即你所要爬取的網(wǎng)站的域名,如:www.baidu.com
創(chuàng)建好爬蟲文件后,打開爬蟲項(xiàng)目下的spiders文件夾坎吻,用編輯器打開我們剛剛創(chuàng)建的爬蟲文件缆蝉。
文件里已經(jīng)定義好了start_urls,這是我們運(yùn)行爬蟲時(shí)要訪問(wèn)的鏈接瘦真。
注意這是一個(gè)列表刊头,可以放入多個(gè)url。
當(dāng)爬蟲運(yùn)行時(shí)就會(huì)一個(gè)一個(gè)地訪問(wèn) start_urls里的鏈接诸尽,然后將返回的響應(yīng)做為參數(shù)傳遞給 parse函數(shù)原杂。
在 parse函數(shù)里,我們可以來(lái)對(duì)網(wǎng)頁(yè)中的信息進(jìn)行提取您机。
示例只爬取一個(gè)頁(yè)面(頭號(hào)玩家的詳情頁(yè))穿肄,代碼如下:
# -*- coding: utf-8 -*-
#movieInfoSpider.py
import scrapy
#導(dǎo)入DouBanItem類
from douban.items import DoubanItem
class MovieinfoSpider(scrapy.Spider):
name = 'movieInfo'
allowed_domains = ['movie.douban.com']
start_urls = ['https://movie.douban.com/subject/4920389/?from=showing']
def parse(self, response):
#創(chuàng)建DoubanItem類
item = DoubanItem()
item['movie_name'] = response.xpath('//title/text()').extract()[0]
item['movie_dir'] = '導(dǎo)演:' + '/'.join(response.xpath('//div[@id="info"]/span[1]/span/a/text()').extract())
item['movie_editors'] = '編劇:' + '/'.join(response.xpath('//div[@id="info"]/span[2]/span/a/text()').extract())
item['movie_actors'] = '主演:' + '/'.join(response.xpath('//div[@id="info"]/span[3]/span/a/text()').extract())
item['movie_type'] = '類型:' + '/'.join(response.xpath('//div[@id="info"]/span[@property=
yield item
提取到所需的信息后,用 yield
關(guān)鍵字將 item傳遞給 pipelines.py進(jìn)行進(jìn)一步的處理
三际看、對(duì)提取到的信息進(jìn)行儲(chǔ)存
pipelines.py文件獲得item后將會(huì)調(diào)用管道函數(shù)來(lái)對(duì)item進(jìn)行處理咸产,這里我們把電影的信息保存到 txt文件中去,代碼如下:
# -*- coding: utf-8 -*-
#pipelines.py
class DoubanPipeline(object):
def __init__(self):
self.fo = open('info.txt', 'wb')
def process_item(self, item, spider):
self.fo.write((item['movie_name'] + '\n').encode('utf-8'))
self.fo.write((item['movie_dir'] + '\n').encode('utf-8'))
self.fo.write((item['movie_editor'] + '\n').encode('utf-8'))
self.fo.write((item['movie_actors'] + '\n').encode('utf-8'))
self.fo.write((item['movie_type'] + '\n').encode('utf-8'))
#這里必須返回item仲闽,否則程序會(huì)一直等待脑溢,直到返回item為止
return item
def close_spider(self, spider):
self.fo.close()
#__init__, 和close_spider 函數(shù)相當(dāng)于c++里的構(gòu)造函數(shù)和析構(gòu)函數(shù)
四、在 setting.py里開啟 DoubanPipeline管道
這里只截取部分相關(guān)的代碼:
# Obey robots.txt rules
#是否遵循網(wǎng)站對(duì)爬蟲的規(guī)則赖欣,一般設(shè)為False屑彻,但默認(rèn)為True
ROBOTSTXT_OBEY = False
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'douban.pipelines.DoubanPipeline': 300,
}
#設(shè)置請(qǐng)求頭,模擬瀏覽器
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Cookie': 'bid=uzUipzgnxdY; ll="118267"; __utmc=30149280; __utmz=30149280.1523088054.4.4.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utmc=223695111; __utmz=223695111.1523088054.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __yadk_uid=u46EFxFlzD46PvWysMULc80N9s8k2pp4; _vwo_uuid_v2=DC94F00058615E2C6A432CB494EEB894B|64bbcc3ac402b9490e5de18ce3216c5f; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1523092410%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DFIqLEYPF6UnylF-ja19vuuKZ51u3u5gGYJHpVJ5MRTO-oLkJ_C84HBgYi5OulPwl%26wd%3D%26eqid%3Dd260482b00005bbb000000055ac87ab2%22%5D; _pk_id.100001.4cf6=cbf515d686eadc0b.1523088053.2.1523092410.1523088087.; _pk_ses.100001.4cf6=*; __utma=30149280.1054682088.1514545233.1523088054.1523092410.5; __utmb=30149280.0.10.1523092410; __utma=223695111.979367240.1523088054.1523088054.1523092410.2; __utmb=223695111.0.10.1523092410',
'Host': 'movie.douban.com',
'Upgrade-Insecure-Requests': '1',
}
五顶吮、運(yùn)行爬蟲
進(jìn)入到爬蟲項(xiàng)目的文件夾里執(zhí)行如下命令:
scrapy crawl movieInfoSpider
總結(jié):scrapy爬蟲構(gòu)建順序 items.py-->spiders-->pipelines.py-->settings.py
原文: https://blog.csdn.net/qq_40695895/article/details/79842502