【Python爬蟲】儲存格式化資料
阿新 • • 發佈:2020-07-14
我們一直使用 print 方法列印爬蟲獲取的資料,接下來你將把這些資料儲存到特定格式檔案中。
CSV 格式
Python 提供了標準庫 csv 來讀寫 csv 資料。
新建一個 Python 檔案,輸入以下程式碼,並執行。
import csv file = open('movies.csv', 'w', newline='') csvwriter = csv.writer(file) # 寫入標題行 csvwriter.writerow(['名稱', '年份']) # 寫入資料 csvwriter.writerow(['A', '1992']) csvwriter.writerow(['B', '1998']) csvwriter.writerow(['C', '2010']) file.close
使用記事本開啟 movies.csv 檔案,將執行結果複製到下面的文字框中:
通常用來儲存簡單的資料,表格型別資料首選
通常用來儲存 「鍵-值」 資料,一般情況下的選擇
儲存非常複雜的資料格式,大多數情況下用不到
CSV 資料可以使用微軟 Office Excel 軟體開啟。非常多的爬蟲資料集都使用 CSV 作為儲存格式。
將爬蟲資料寫入 CSV 檔案
至此,你已經基本掌握了編寫一個簡單爬蟲的技能,是不是很簡單呢?
from requests_html import HTMLSession import csv session = HTMLSession() file = open('movies.csv', 'w', newline='') csvwriter = csv.writer(file) csvwriter.writerow(['名稱', '年份']) links = ['https://movie.douban.com/subject/1292052/', 'https://movie.douban.com/subject/26752088/', 'https://movie.douban.com/subject/1962665/'] for link in links: r = session.get(link) title = r.html.find('#content > h1 > span:nth-child(1)', first=True) year = r.html.find('#content > h1 > span.year', first=True) csvwriter.writerow(title.text, year.text) file.close()
上面程式碼有一處錯誤,你發現了嗎?
執行結果: