Pandas爬蟲,竟能如此簡單!

pandas中的pd.read_html()這個函數(shù),功能非常強大,可以輕松實現(xiàn)抓取Table表格型數(shù)據(jù)。無需掌握正則表達式或者xpath等工具,短短的幾行代碼就可以將網(wǎng)頁數(shù)據(jù)抓取下來。


Table表格一般網(wǎng)頁結構

針對網(wǎng)頁結構類似的表格類型數(shù)據(jù),pd.read_html可以將網(wǎng)頁上的表格數(shù)據(jù)都抓取下來,并以DataFrame的形式裝在一個list中返回。
三.pd.read_html語法及參數(shù)
基本語法
主要參數(shù)
1import pandas as pd
2import csv
3url1 = 'http://www.compassedu.hk/qs'
4df1 = pd.read_html(url1)[0] #0表示網(wǎng)頁中的第一個Table
5df1.to_csv('世界大學綜合排名.csv',index=0)

二.案例2:抓取新浪財經(jīng)基金重倉股數(shù)據(jù)(6頁數(shù)據(jù))
1import pandas as pd
2import csv
3df2 = pd.DataFrame()
4for i in range(6):
5 url2 = 'http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jjzc/index.phtml?p={page}'.format(page=i+1)
6 df2 = pd.concat([df2,pd.read_html(url2)[0]])
7 print('第{page}頁抓取完成'.format(page = i + 1))
8df2.to_csv('./新浪財經(jīng)數(shù)據(jù).csv',encoding='utf-8',index=0)
沒錯,8行代碼搞定,還是那么簡單。如果對翻頁爬蟲不理解,可查看本公眾號歷史原創(chuàng)文章「實戰(zhàn)|手把手教你用Python爬蟲(附詳細源碼)」,如果對DataFrame合并不理解,可查看本公眾號歷史原創(chuàng)文章「基礎|Pandas常用知識點匯總(四)」。
我們來預覽下爬取到的數(shù)據(jù):

基金重倉股數(shù)據(jù)
三.案例3:抓取證監(jiān)會披露的IPO數(shù)據(jù)(217頁數(shù)據(jù))
1import pandas as pd
2from pandas import DataFrame
3import csv
4import time
5start = time.time() #計時
6df3 = DataFrame(data=None,columns=['公司名稱','披露日期','上市地和板塊','披露類型','查看PDF資料']) #添加列名
7for i in range(1,218):
8 url3 ='http://eid.csrc.gov.cn/ipo/infoDisplay.action?pageNo=%s&temp=&temp1=&blockType=byTime'%str(i)
9 df3_1 = pd.read_html(url3,encoding='utf-8')[2] #必須加utf-8,否則亂碼
10 df3_2 = df3_1.iloc[1:len(df3_1)-1,0:-1] #過濾掉最后一行和最后一列(NaN列)
11 df3_2.columns=['公司名稱','披露日期','上市地和板塊','披露類型','查看PDF資料'] #新的df添加列名
12 df3 = pd.concat([df3,df3_2]) #數(shù)據(jù)合并
13 print('第{page}頁抓取完成'.format(page=i))
14df3.to_csv('./上市公司IPO信息.csv', encoding='utf-8',index=0) #保存數(shù)據(jù)到csv文件
15end = time.time()
16print ('共抓取',len(df3),'家公司,' + '用時',round((end-start)/60,2),'分鐘')
這里注意要對抓下來的Table數(shù)據(jù)進行過濾,主要用到iloc方法,詳情可查看本公眾號往期原創(chuàng)文章「基礎|Pandas常用知識點匯總(三)」。另外,我還加了個程序計時,方便查看爬取速度。

2分鐘爬下217頁4334條數(shù)據(jù),相當nice了。我們來預覽下爬取到的數(shù)據(jù):

上市公司IPO數(shù)據(jù)
需要注意的是,并不是所有表格都可以用pd.read_html爬取,有的網(wǎng)站表面上看起來是表格,但在網(wǎng)頁源代碼中不是table格式,而是list列表格式。這種表格則不適用read_html爬取,得用其他的方法,比如selenium。

相關閱讀:
