秀!Pandas 也能爬虫!
談及 Pandas 的 read.xxx 系列的函數(shù),大家的第一反應(yīng)會(huì)想到比較常用的 pd.read_csv() 和 pd.read_excel(),大多數(shù)人估計(jì)沒(méi)用過(guò) pd.read_html() 這個(gè)函數(shù)。雖然它低調(diào),但功能非常強(qiáng)大,用于抓取Table表格型數(shù)據(jù)時(shí),簡(jiǎn)直是個(gè)神器。
是的,這個(gè)神器可以用來(lái)爬蟲(chóng)!
本文目錄
定 義
pd.read_html() 這個(gè)函數(shù)功能強(qiáng)大,無(wú)需掌握正則表達(dá)式或者 xpath 等工具,短短的幾行代碼就可以輕松實(shí)現(xiàn)抓取 Table 表格型網(wǎng)頁(yè)數(shù)據(jù)。
原 理
一.Table 表格型數(shù)據(jù)網(wǎng)頁(yè)結(jié)構(gòu)
為了了解 Table 網(wǎng)頁(yè)結(jié)構(gòu),我們看個(gè)簡(jiǎn)單例子。
指南者留學(xué)網(wǎng)
沒(méi)錯(cuò),簡(jiǎn)單!
另一個(gè)例子:
新浪財(cái)經(jīng)網(wǎng)
規(guī)律:以 Table 結(jié)構(gòu)展示的表格數(shù)據(jù),網(wǎng)頁(yè)結(jié)構(gòu)長(zhǎng)這樣:
<table class="..." id="...">
? ? ?<thead>
? ? ?<tr>
? ? ?<th>...</th>
? ? ?</tr>
? ? ?</thead>
? ? ?<tbody>
? ? ? ? <tr>
? ? ? ? ? ? <td>...</td>
? ? ? ? </tr>
? ? ? ? <tr>...</tr>
? ? ? ? <tr>...</tr>
? ? ? ? ...
? ? ? ? <tr>...</tr>
? ? ? ? <tr>...</tr>? ? ? ??
? ? </tbody>
</table>
Table 表格一般網(wǎng)頁(yè)結(jié)構(gòu)
二.pandas 請(qǐng)求表格數(shù)據(jù)原理
基本流程
其實(shí),pd.read_html?可以將網(wǎng)頁(yè)上的表格數(shù)據(jù)都抓取下來(lái),并以 DataFrame 的形式裝在一個(gè) list 中返回。
三.pd.read_html?語(yǔ)法及參數(shù)
pandas.read_html(io, match='.+',?flavor=None,?
header=None,index_col=None,skiprows=None,?
attrs=None, parse_dates=False, thousands=', ',?
encoding=None, decimal='.', converters=None, na_values=None,?
keep_default_na=True, displayed_only=True)
基本語(yǔ)法
io?:接收網(wǎng)址、文件、字符串;
parse_dates:解析日期;
flavor:解析器;
header:標(biāo)題行;
skiprows:跳過(guò)的行;
attrs:屬性,比如 attrs = {'id': 'table'}
主要參數(shù)
實(shí) 戰(zhàn)
一.案例1:抓取世界大學(xué)排名(1 頁(yè)數(shù)據(jù))
5 行代碼,幾秒鐘就搞定,數(shù)據(jù)預(yù)覽:
世界大學(xué)排行榜
二.案例 2:抓取新浪財(cái)經(jīng)基金重倉(cāng)股數(shù)據(jù)(6 頁(yè)數(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}頁(yè)抓取完成'.format(page?=?i?+?1)) 8df2.to_csv('./新浪財(cái)經(jīng)數(shù)據(jù).csv',encoding='utf-8',index=0)8 行代碼搞定,還是那么簡(jiǎn)單。
我們來(lái)預(yù)覽下爬取到的數(shù)據(jù):
基金重倉(cāng)股數(shù)據(jù)
三.案例3:抓取證監(jiān)會(huì)披露的?IPO?數(shù)據(jù)(217 頁(yè)數(shù)據(jù))
1import?pandas?as?pd2from?pandas?import?DataFrame3import?csv4import?time5start?=?time.time()?#計(jì)時(shí)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]??#過(guò)濾掉最后一行和最后一列(NaN列) 11????df3_2.columns=['公司名稱','披露日期','上市地和板塊','披露類型','查看PDF資料']?#新的df添加列名 12????df3?=?pd.concat([df3,df3_2])??#數(shù)據(jù)合并 13????print('第{page}頁(yè)抓取完成'.format(page=i)) 14df3.to_csv('./上市公司IPO信息.csv',?encoding='utf-8',index=0)?#保存數(shù)據(jù)到csv文件 15end?=?time.time() 16print?('共抓取',len(df3),'家公司,'?+?'用時(shí)',round((end-start)/60,2),'分鐘')這里注意要對(duì)抓下來(lái)的 Table 數(shù)據(jù)進(jìn)行過(guò)濾,主要用到 iloc 方法。另外,我還加了個(gè)程序計(jì)時(shí),方便查看爬取速度。
2 分鐘爬下 217 頁(yè) 4334 條數(shù)據(jù),相當(dāng) nice 了。我們來(lái)預(yù)覽下爬取到的數(shù)據(jù):
上市公司IPO數(shù)據(jù)
注意,并不是所有表格都可以用 pd.read_html 爬取,有的網(wǎng)站表面上看起來(lái)是表格,但在網(wǎng)頁(yè)源代碼中不是 table 格式,而是 list 列表格式。這種表格則不適用 read_html 爬取,得用其他的方法,比如 selenium。
對(duì)比Excel系列圖書累積銷量達(dá)15w冊(cè),讓你輕松掌握數(shù)據(jù)分析技能,感興趣的同學(xué)可以直接在各大電商平臺(tái)搜索書名了解:
總結(jié)
以上是生活随笔為你收集整理的秀!Pandas 也能爬虫!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: r是左边还是右边(Project)
- 下一篇: 抖音限流怎么看的出来
