如何爬取中國近十年的GDP,並寫入csv檔案?

2021-10-14 15:54:31 字數 3544 閱讀 8203

怎樣爬取中國近十年的gdp,看看中國經濟的變化,進而做出視覺化圖呢?這裡我們先教大家第一步,獲取資料,資料是基礎。

: # 信任所有https的安全證書

('程式出錯'

)這裡要對應**原始碼去檢視,獲取對應的div,table下的資料

def get_data

(html)

: # 定義乙個空列表,存放資料的屬性(頭部標題)

data_header =

# 定義乙個空列表,存放資料

data_detail =

# 是指定beautiful的解析器為html.parser

soup =

beautifulsoup

(html,

'html.parser'

) # 得到最小的那個類標籤以內的html

table_divs = soup.

find

('div',)

# 得到最小類下的table

table_divs1 = table_divs.

find

('table',)

# 得到table下的thead

thead = table_divs1.

find

('thead'

) # 得到thead下的th

ths = thead.

find_all

('th'

)for th in ths:

header = th.text.

strip()

data_header.

(header)

# 得到table下的tbody

tbody = table_divs1.

find

('tbody'

) # 得到tbody下的td

tds = tbody.

find_all

('td'

) # 獲取2010

-2023年的資料

for td in tds[0:

30]:if td !=none:

detail = td.text.

strip(''

) data_detail.

(detail)

else

: pass

# 返回值

return

(data_header, data_detail)

def data_write

(data_h, data_d)

:with

open

('china_data1_0.csv'

, mode=

'w', encoding=

'utf-8'

,newline='')

as f:

# 基於檔案物件構建csv寫入物件

csv_writer = csv.

writer

(f) # 先將頭部寫入列表

csv_writer.

writerow

(data_h)

# 為保證資料格式,將列表分割好

for i in

range(0

,len

(data_d),3

):# 去除空行

if i !='':

csv_writer.

writerow

(data_d[i:i+3]

) # print

('爬取完成,請到china_data.csv檢視'

)

url =

""html =

exception_handling

(url)

if html != none:

get_data

(html)

data_h, data_d =

get_data

(html)

data_write

(data_h, data_d)

以上便是全部內容,資料出來會發現,資料是原始的資料,如下:

年份,中國,gdp(美元),佔世界%

2019,「14.34萬億 (14,342,902,842,915)」,16.3550%

2018,「13.89萬億 (13,894,817,110,036)」,16.0900%

2017,「12.31萬億 (12,310,408,652,423)」,15.1552%

2016,「11.23萬億 (11,233,277,146,512)」,14.7156%

2015,「11.06萬億 (11,061,552,790,044)」,14.7098%

2014,「10.48萬億 (10,475,682,846,632)」,13.1851%

2013,「9.57萬億 (9,570,405,758,739)」,12.3805%

2012,「8.53萬億 (8,532,230,724,141)」,11.3542%

2011,「7.55萬億 (7,551,500,425,597)」,10.2814%

2010,「6.09萬億 (6,087,164,527,421)」,9.2072%

下一鏈結我們將會講述,如何將資料規範化,變成我們可用的資料。感謝大家閱讀菜鳥遠遠的部落格。喜歡的小夥伴收藏加點贊叭。

我廠近十年來的慘敗

2008年1月23日 聯賽杯半決賽 熱刺 5 1 阿森納 連續21場交手沒贏過阿森納的熱刺,9年後首度擊敗北倫敦近鄰。開場3分鐘耶納斯遠射首開紀錄,26分鐘本特納烏龍宴客。下半場又是開場3分鐘基恩大力抽射繼續添分,60分鐘熱刺快速反擊基恩推傳列農單刀破門。70分鐘阿德巴約憑藉個人能力扳回一球,但終場...

南韓或終結近十年的青少年網遊宵禁條例

南韓先驅報 報道稱,程式設計客棧該國正在終結頒布已近十年的青少程式設計客棧年網路遊戲宵禁條例。此前根據當地的 青少年保護修訂法案 又稱 灰姑娘法 網路 遊戲廠商不得在凌晨 0 點至上午 6 點這個時間段,向 16 歲以下的未成年人非法提供服務。最新訊息是,在週三於首爾舉辦的線上新聞發布會期間,南韓文...

Web 發展的十年

當時您在 級別 初級 chris walden 內容採集編輯,developerworks,ibm 2009 年 11 月 23 日 developerworks 在十年之間貢獻了許多資料。回首技術歷程,我們將看到哪些方面發生了變化。我們將回顧多彩的過去以及當時流行文化中發生的變化,讓您全面了解這段...