爬蟲將爬取到的 信息 存儲進excel表中
1.直接寫入的方式
filename excel文件名, sheetname 就是你的 excel表格底下的 sheet ,wordlist 你的數據
import xlwt # 往excel寫入
def write_to_excel(self, filename, sheetname, word_list):
print(word_list)
try:
# 創建workbook
workbook = xlwt.Workbook(encoding='utf-8')
# 給工作表中添加sheet表單
sheet = workbook.add_sheet(sheetname)
# 設置表頭
head = []
print(head)
for i in word_list[0].keys():
head.append(i)
# 將表頭寫入excel
for j in range(len(head)):
sheet.write(0, j, head[j])
# 給表中寫入內容
x = 1
for item in word_list:
for y in range(len(head)):
sheet.write(x, y, item[head[y]])
x += 1
# 保存
workbook.save(filename)
print("寫入成功")
except Exception:
print('寫入失敗')
2.往excel中追加
import xlrd # 往excel中追加
from xlutils.copy import copy # 需要使用的 一個 工具包
def write_to_excel_append(filename,infos):
'''
追加excel的方法
:param filename: 文件名
:param infos: 【item,item】
:return:
'''
#打開excle文件
work_book = xlrd.open_workbook(filename)
#獲取工作表中的所有sheet表單名稱
sheets = work_book.sheet_names()
#獲取第一個表單
work_sheet = work_book.sheet_by_name(sheets[0])
#獲取已經寫入的行數
old_rows = work_sheet.nrows
#獲取表頭的所有字段
keys = work_sheet.row_values(0)
#將xlrd對象轉化成xlwt,為了寫入
new_work_book = copy(work_book)
#獲取表單來添加數據
new_sheet = new_work_book.get_sheet(0)
i = old_rows
for item in infos:
for j in range(len(keys)):
new_sheet.write(i, j, item[keys[j]])
i += 1
new_work_book.save(filename)
print('追加成功!')
