爬蟲成長之路(一)里我們介紹了如何爬取證券之星網站上所有A股數據,主要涉及網頁獲取和頁面解析的知識。爬蟲成長之路(二)里我們介紹了如何獲取代理IP並驗證,涉及了多線程編程和數據存儲的知識。此次我們將在前兩節的基礎上,對證券之星全站的行情數據進行爬取。第一節的思路爬一個欄目的數據尚可,爬上百個欄目的數據工作量就有點大了。下面我們先介紹下基礎的爬蟲架構。
本文主要包含爬蟲框架六大基礎模塊,分別為爬蟲調度器、URL下載器、URL管理器、HTML下載器、HTML解析器、數據存儲器。功能分析如下
爬蟲調度器:主要負責統籌其他四個模塊的工作。
URL下載器:主要負責下載需要爬取數據的URL鏈接。
URL管理器:負責管理URL鏈接,維護已經爬取的URL集合和未爬取的URL集合,提供獲取新URL鏈接的接口。
HTML下載器:用於從URL管理器中獲取未爬取的URL鏈接並下載HRML網頁。
HTML解析器:用戶從HTML下載器中獲取已經下載的HTML網頁,解析出有效數據交給數據存儲器。
數據存儲器:用於將HTML解析器解析出來的數據通過文件或者數據庫的形式儲存起來。
為了方便理解,以下是基礎爬蟲框架運行流程示意圖
此處介紹文件夾,下面,我們對這6大模塊進行詳細的介紹。
一、URL下載器
URL下載器包含兩步,首先下載網站左側導航欄的URL,然后通過導航欄的URL獲取每個子欄目包含的鏈接列表。

下面是獲取左側導航欄所有鏈接並生成導航文件的代碼
# -*- coding: utf-8 -*- import pandas as pd import urllib.request from bs4 import BeautifulSoup import re import os class get_catalog(object): '''生成和操作導航文件''' def save_catalog(self): '''獲得證券之星左側自導航的內容和網址並保存''' #獲取網頁內容 url = 'http://quote.stockstar.com' request =urllib.request.Request(url = url) response = urllib.request.urlopen(request) content = response.read().decode('gbk') #截取左側導航內容 soup = BeautifulSoup(content,"lxml") soup = BeautifulSoup(str(soup.find_all('div',class_ = "subMenuBox")),"lxml") #初始化一級子目錄和二級子目錄的數據框 catalog1 = pd.DataFrame(columns = ["cata1","cata2","url2"]) catalog2 = pd.DataFrame(columns = ["url2","cata3","url3"]) #整理目錄內容和其對應的鏈接 index1 = 0;index2 = 0 for content1 in soup.find_all('div',class_ = re.compile("list submenu?")): cata1 = re.findall('>(.*?)<',str(content1.h3.a)) for content2 in content1.find_all('dl'): cata2 = re.findall('>(.*?)<',str(content2.dt.a).replace('\r\n','')) url2 = url + content2.dt.a['href'] catalog1.loc[index1] = {'cata1':cata1[0],'cata2':cata2[0].split()[0],'url2':url2} index1 += 1 for content3 in content2.find_all('li'): cata3 = re.findall('·(.*?)<',str(content3.a)) url3 = url + content3.a['href'] catalog2.loc[index2] = {'url2':url2,'cata3':cata3[0],'url3':url3} index2 += 1 #對一級子目錄表和二級子目錄表做表連接並保存 catalog = pd.merge(catalog1,catalog2,on='url2',how='left') catalog.to_csv('catalog.csv') def load_catalog(self): '''判斷導航文件是否存在並載入''' if 'catalog.csv' not in os.listdir(): self.save_catalog() print('網址導航文件已生成') else: print('網址導航文件已存在') catalog = pd.read_csv('catalog.csv',encoding='gbk',usecols=range(1,6)) print("網址導航文件已載入") return(catalog) def index_info(self,catalog,index): '''創建每行的行名,作為存入數據庫的表名,並獲取每行終端的網址鏈接''' if str(catalog.loc[index]['cata3'])=='nan': table_name = catalog.loc[index]['cata1'] + '_' + catalog.loc[index]['cata2'] url = catalog.loc[index]['url2'] else: #+、()等符號不能作為數據庫表名,得替換或剔除 if '+' in catalog.loc[index]['cata3']: cata3 = catalog.loc[index]['cata3'].replace('+','') table_name = catalog.loc[index]['cata1'] + '_' + catalog.loc[index][