python爬蟲scrapy圖書分類實(shí)例講解
我們?nèi)D書館的時(shí)候,會直接去自己喜歡的分類欄目找尋書籍。如果其中的分類不是很細(xì)致的話,想找某一本書還是有一些困難的。同樣的如果我們獲取了一些圖書的數(shù)據(jù),原始的文件里各種數(shù)據(jù)混雜在一起,非常不利于我們的查找和使用。所以今天小編教大家如何用python爬蟲中scrapy給圖書分類,大家一起學(xué)習(xí)下:
spider抓取程序:
在貼上代碼之前,先對抓取的頁面和鏈接做一個(gè)分析:
網(wǎng)址:http://category.dangdang.com/pg4-cp01.25.17.00.00.00.html
這個(gè)是當(dāng)當(dāng)網(wǎng)圖書的鏈接,經(jīng)過分析發(fā)現(xiàn):大種類的id號對應(yīng) cp01.25 中的25,小種類對應(yīng)id號中的第三個(gè) 17,pg4代表大種類 —>小種類下圖書的第17頁信息。
為了在抓取圖書信息的同時(shí)找到這本圖書屬于哪一大種類下的小種類的歸類信息,我們需要分三步走,第一步:大種類劃分,在首頁找到圖書各大種類名稱和對應(yīng)的id號;第二步,根據(jù)大種類id號生成的鏈接,找到每個(gè)大種類下的二級子種類名稱,及對應(yīng)的id號;第三步,在大種類 —>小種類的歸類下抓取每本圖書信息。
分步驟介紹下:
1、我們繼承RedisSpider作為父類,start_urls作為初始鏈接,用于請求首頁圖書數(shù)據(jù)
# -*- coding: utf-8 -*- import scrapy import requests from scrapy import Selector from lxml import etree from ..items import DangdangItem from scrapy_redis.spiders import RedisSpider class DangdangSpider(RedisSpider): name = 'dangdangspider' redis_key = 'dangdangspider:urls' allowed_domains = ["dangdang.com"] start_urls = 'http://category.dangdang.com/cp01.00.00.00.00.00.html' def start_requests(self): user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 \ Safari/537.36 SE 2.X MetaSr 1.0' headers = {'User-Agent': user_agent} yield scrapy.Request(url=self.start_urls, headers=headers, method='GET', callback=self.parse)
2、在首頁中抓取大種類的名稱和id號,其中yield回調(diào)函數(shù)中傳入的meta值為本次匹配出的大種類的名稱和id號
def parse(self, response): user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 \ Safari/537.36 SE 2.X MetaSr 1.0' headers = {'User-Agent': user_agent} lists = response.body.decode('gbk') selector = etree.HTML(lists) goodslist = selector.xpath('//*[@id="leftCate"]/ul/li') for goods in goodslist: try: category_big = goods.xpath('a/text()').pop().replace(' ','') # 大種類 category_big_id = goods.xpath('a/@href').pop().split('.')[1] # id category_big_url = "http://category.dangdang.com/pg1-cp01.{}.00.00.00.00.html".\ format(str(category_big_id)) # print("{}:{}".format(category_big_url,category_big)) yield scrapy.Request(url=category_big_url, headers=headers,callback=self.detail_parse, meta={"ID1":category_big_id,"ID2":category_big}) except Exception: Pass
3、根據(jù)傳入的大種類的id號抓取每個(gè)大種類下的小種類圖書標(biāo)簽,yield回調(diào)函數(shù)中傳入的meta值為大種類id號和小種類id號
def detail_parse(self, response): ID1:大種類ID ID2:大種類名稱 ID3:小種類ID ID4:小種類名稱 url = 'http://category.dangdang.com/pg1-cp01.{}.00.00.00.00.html'.format(response.meta["ID1"]) category_small = requests.get(url) contents = etree.HTML(category_small.content.decode('gbk')) goodslist = contents.xpath('//*[@class="sort_box"]/ul/li[1]/div/span') for goods in goodslist: try: category_small_name = goods.xpath('a/text()').pop().replace(" ","").split('(')[0] category_small_id = goods.xpath('a/@href').pop().split('.')[2] category_small_url = "http://category.dangdang.com/pg1-cp01.{}.{}.00.00.00.html".\ format(str(response.meta["ID1"]),str(category_small_id)) yield scrapy.Request(url=category_small_url, callback=self.third_parse, meta={"ID1":response.meta["ID1"],\ "ID2":response.meta["ID2"],"ID3":category_small_id,"ID4":category_small_name}) # print("============================ {}".format(response.meta["ID2"])) # 大種類名稱 # print(goods.xpath('a/text()').pop().replace(" ","").split('(')[0]) # 小種類名稱 # print(goods.xpath('a/@href').pop().split('.')[2]) # 小種類ID except Exception: Pass
4、抓取各大種類——>小種類下的圖書信息
def third_parse(self,response): for i in range(1,101): url = 'http://category.dangdang.com/pg{}-cp01.{}.{}.00.00.00.html'.format(str(i),response.meta["ID1"],\ response.meta["ID3"]) try: contents = requests.get(url) contents = etree.HTML(contents.content.decode('gbk')) goodslist = contents.xpath('//*[@class="list_aa listimg"]/li') for goods in goodslist: item = DangdangItem() try: item['comments'] = goods.xpath('div/p[2]/a/text()').pop() item['title'] = goods.xpath('div/p[1]/a/text()').pop() item['time'] = goods.xpath('div/div/p[2]/text()').pop().replace("/", "") item['price'] = goods.xpath('div/p[6]/span[1]/text()').pop() item['discount'] = goods.xpath('div/p[6]/span[3]/text()').pop() item['category1'] = response.meta["ID4"] # 種類(小) item['category2'] = response.meta["ID2"] # 種類(大) except Exception: pass yield item except Exception: pass
到此這篇關(guān)于python爬蟲scrapy圖書分類實(shí)例講解的文章就介紹到這了,更多相關(guān)python爬蟲中scrapy如何給圖書分類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python常見庫matplotlib學(xué)習(xí)筆記之畫圖文字的中文顯示
在Python中使用matplotlib或者plotnine模塊繪圖時(shí),常常出現(xiàn)圖表中無法正常顯示中文的問題,下面這篇文章主要給大家介紹了關(guān)于Python常見庫matplotlib學(xué)習(xí)筆記之畫圖文字的中文顯示的相關(guān)資料,需要的朋友可以參考下2023-05-05如何利用python寫GUI及生成.exe可執(zhí)行文件
工作中需要開發(fā)一個(gè)小工具,簡單的UI界面可以很好的提高工具的實(shí)用性,由此開啟了我的第一次GUI開發(fā)之旅,這篇文章主要給大家介紹了關(guān)于如何利用python寫GUI及生成.exe可執(zhí)行文件的相關(guān)資料,需要的朋友可以參考下2021-12-12django-rest-swagger對API接口注釋的方法
今天小編就為大家分享一篇django-rest-swagger對API接口注釋的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08Python運(yùn)行第一個(gè)PySide2的窗體程序
本文主要介紹了Python運(yùn)行第一個(gè)PySide2的窗體程序,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07pytorch 實(shí)現(xiàn)查看網(wǎng)絡(luò)中的參數(shù)
今天小編就為大家分享一篇pytorch 實(shí)現(xiàn)查看網(wǎng)絡(luò)中的參數(shù),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python實(shí)現(xiàn).gif圖片拆分為.png圖片的簡單示例
有時(shí)候需要把GIF圖片分解成一張一張的靜態(tài)圖,jpg或者png格式,下面這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn).gif圖片拆分為.png圖片的相關(guān)資料,需要的朋友可以參考下2023-01-01基于python實(shí)現(xiàn)圖書管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于python實(shí)現(xiàn)圖書管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04