爬取目標(biāo)站點(diǎn)分析
本次采集的目標(biāo)站點(diǎn)為:https://www.zaih.com/falcon/mentors,目標(biāo)數(shù)據(jù)為在行高手?jǐn)?shù)據(jù)。
本次數(shù)據(jù)保存到 MySQL 數(shù)據(jù)庫中,基于目標(biāo)數(shù)據(jù),設(shè)計(jì)表結(jié)構(gòu)如下所示。
對比表結(jié)構(gòu),可以直接將 scrapy 中的 items.py 文件編寫完畢。
class ZaihangItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() # 姓名 city = scrapy.Field() # 城市 industry = scrapy.Field() # 行業(yè) price = scrapy.Field() # 價格 chat_nums = scrapy.Field() # 聊天人數(shù) score = scrapy.Field() # 評分
編碼時間
項(xiàng)目的創(chuàng)建過程參考上一案例即可,本文直接從采集文件開發(fā)進(jìn)行編寫,該文件為 zh.py。
本次目標(biāo)數(shù)據(jù)分頁地址需要手動拼接,所以提前聲明一個實(shí)例變量(字段),該字段為 page,每次響應(yīng)之后,判斷數(shù)據(jù)是否為空,如果不為空,則執(zhí)行 +1 操作。
請求地址模板如下:
https://www.zaih.com/falcon/mentors?first_tag_id=479&first_tag_name=心理&page={}
當(dāng)頁碼超過最大頁數(shù)時,返回如下頁面狀態(tài),所以數(shù)據(jù)為空狀態(tài),只需要判斷 是否存在 class=empty 的 section 即可。
解析數(shù)據(jù)與數(shù)據(jù)清晰直接參考下述代碼即可。
import scrapy from zaihang_spider.items import ZaihangItem class ZhSpider(scrapy.Spider): name = 'zh' allowed_domains = ['www.zaih.com'] page = 1 # 起始頁碼 url_format = 'https://www.zaih.com/falcon/mentors?first_tag_id=479&first_tag_name=%E5%BF%83%E7%90%86&page={}' # 模板 start_urls = [url_format.format(page)] def parse(self, response): empty = response.css("section.empty") # 判斷數(shù)據(jù)是否為空 if len(empty) > 0: return # 存在空標(biāo)簽,直接返回 mentors = response.css(".mentor-board a") # 所有高手的超鏈接 for m in mentors: item = ZaihangItem() # 實(shí)例化一個對象 name = m.css(".mentor-card__name::text").extract_first() city = m.css(".mentor-card__location::text").extract_first() industry = m.css(".mentor-card__title::text").extract_first() price = self.replace_space(m.css(".mentor-card__price::text").extract_first()) chat_nums = self.replace_space(m.css(".mentor-card__number::text").extract()[0]) score = self.replace_space(m.css(".mentor-card__number::text").extract()[1]) # 格式化數(shù)據(jù) item["name"] = name item["city"] = city item["industry"] = industry item["price"] = price item["chat_nums"] = chat_nums item["score"] = score yield item # 再次生成一個請求 self.page += 1 next_url = format(self.url_format.format(self.page)) yield scrapy.Request(url=next_url, callback=self.parse) def replace_space(self, in_str): in_str = in_str.replace("\n", "").replace("\r", "").replace("¥", "") return in_str.strip()
開啟 settings.py 文件中的 ITEM_PIPELINES,注意類名有修改
ITEM_PIPELINES = { 'zaihang_spider.pipelines.ZaihangMySQLPipeline': 300, }
修改 pipelines.py 文件,使其能將數(shù)據(jù)保存到 MySQL 數(shù)據(jù)庫中
在下述代碼中,首先需要了解類方法 from_crawler,該方法是 __init__ 的一個代理,如果其存在,類被初始化時會被調(diào)用,并得到全局的 crawler,然后通過 crawler 就可以獲取 settings.py 中的各個配置項(xiàng)。
除此之外,還存在一個 from_settings 方法,一般在官方插件中也有應(yīng)用,示例如下所示。
@classmethod def from_settings(cls, settings): host= settings.get('HOST') return cls(host) @classmethod def from_crawler(cls, crawler): # FIXME: for now, stats are only supported from this constructor return cls.from_settings(crawler.settings)
在編寫下述代碼前,需要提前在 settings.py 中寫好配置項(xiàng)。
settings.py 文件代碼
HOST = "127.0.0.1" PORT = 3306 USER = "root" PASSWORD = "123456" DB = "zaihang"
pipelines.py 文件代碼
import pymysql class ZaihangMySQLPipeline: def __init__(self, host, port, user, password, db): self.host = host self.port = port self.user = user self.password = password self.db = db self.conn = None self.cursor = None @classmethod def from_crawler(cls, crawler): return cls( host=crawler.settings.get('HOST'), port=crawler.settings.get('PORT'), user=crawler.settings.get('USER'), password=crawler.settings.get('PASSWORD'), db=crawler.settings.get('DB') ) def open_spider(self, spider): self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.db) def process_item(self, item, spider): # print(item) # 存儲到 MySQL name = item["name"] city = item["city"] industry = item["industry"] price = item["price"] chat_nums = item["chat_nums"] score = item["score"] sql = "insert into users(name,city,industry,price,chat_nums,score) values ('%s','%s','%s',%.1f,%d,%.1f)" % ( name, city, industry, float(price), int(chat_nums), float(score)) print(sql) self.cursor = self.conn.cursor() # 設(shè)置游標(biāo) try: self.cursor.execute(sql) # 執(zhí)行 sql self.conn.commit() except Exception as e: print(e) self.conn.rollback() return item def close_spider(self, spider): self.cursor.close() self.conn.close()
管道文件中三個重要函數(shù),分別是 open_spider,process_item,close_spider。
# 爬蟲開啟時執(zhí)行,只執(zhí)行一次 def open_spider(self, spider): # spider.name = "橡皮擦" # spider對象動態(tài)添加實(shí)例變量,可以在spider模塊中獲取該變量值,比如在 parse(self, response) 函數(shù)中通過self 獲取屬性 # 一些初始化動作 pass # 處理提取的數(shù)據(jù),數(shù)據(jù)保存代碼編寫位置 def process_item(self, item, spider): pass # 爬蟲關(guān)閉時執(zhí)行,只執(zhí)行一次,如果爬蟲運(yùn)行過程中發(fā)生異常崩潰,close_spider 不會執(zhí)行 def close_spider(self, spider): # 關(guān)閉數(shù)據(jù)庫,釋放資源 pass
爬取結(jié)果展示
以以上就是python實(shí)戰(zhàn)項(xiàng)目scrapy管道學(xué)習(xí)爬取在行高手?jǐn)?shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于python scrapy管道學(xué)習(xí)爬取在行的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/hihell/article/details/120934425