date: 2017-02-14 17:05:03
一個(gè)完整的(大)數(shù)據(jù)處理可以分為這幾個(gè)階段:
- 數(shù)據(jù)收集
- 數(shù)據(jù)存儲
- 數(shù)據(jù)建模
- 數(shù)據(jù)分析
- 數(shù)據(jù)變現(xiàn)。
Holi的項(xiàng)目進(jìn)度,已經(jīng)從入門到處理了。
第一步的數(shù)據(jù)收集基本已經(jīng)完成。
現(xiàn)在是第二步的數(shù)據(jù)存儲。
講道理,不懂點(diǎn)前端知識還真不好下手。
看到一堆標(biāo)簽也是很煩的,還好這些東西就想剝洋蔥一樣,一層一層剝開。
配合上《愛麗絲夢游仙境》的BeautifulSoup,就方便多了。
CSV( Comma-Separated Values,逗號分隔值)是存儲表格數(shù)據(jù)的常用文件格式。
Microsoft Excel 和很多應(yīng)用都支持 CSV 格式,因?yàn)樗芎啙崱?/p>
Python 的 csv 庫可以非常簡單地修改 CSV 文件,甚至從零開始創(chuàng)建一個(gè) CSV 文件:
import csv
csvFile = open("../files/test.csv", 'w+')
try:
writer = csv.writer(csvFile)
writer.writerow(('number', 'number plus 2', 'number times 2'))
for i in range(10):
writer.writerow( (i, i+2, i*2))
finally:
csvFile.close()
這種方案來處理教務(wù)處的數(shù)據(jù),就很方便。
這里拿處理課表的來說。
解析課表的網(wǎng)頁源碼會看到有一個(gè)table的標(biāo)簽,這個(gè)很重要。
<table id="tableObj" width="99%" border="0" cellspacing="0" cellpadding="0" class="arranging_arrange">
確定了table和class,就看開始剝洋蔥了。
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("課表url")
bsObj = BeautifulSoup(html)
# 看網(wǎng)頁源碼的class
table = bsObj.findAll("table",{"class":"arranging_arrange"})[0]
#剝第一層洋蔥
rows = table.findAll("tr")
#存儲CSV
csvFile = open("../files/editors.csv", 'wt', newline='', encoding='utf-8')
writer = csv.writer(csvFile)
try:
for row in rows:
csvRow = []
#繼續(xù)一層層剝洋蔥
for cell in row.findAll(['td', 'th']):
csvRow.append(cell.get_text())
writer.writerow(csvRow)
finally:
csvFile.close()
這樣就可以得到存儲在當(dāng)前目錄的CSV文件了。
用Notepad++打開可以看,用excel打開會亂碼。
虐狗節(jié),擼代碼,還有誰。
哈哈哈哈。