­

Python爬虫爬数据写入到EXCEL中

Python抓数据写到EXCEL中。以前都是写到txt中然后再导入到excel。现在直接写到excel中。

#coding=utf-8  import xlwt  import requests  from bs4 import BeautifulSoup  import sys  reload(sys)    sys.setdefaultencoding('utf8')   #打开excel文件  data=xlwt.Workbook()  #获取其中的一个sheet  table=data.add_sheet('made')  # table.put_cell(0,2,1,'why',0)  # nrows=table.nrows  # ncols=table.ncols  # for i in range(nrows):  # 	print table.row_values(i)  r=requests.get('http://html-color-codes.info/color-names/')  html=r.text  #print html  soup=BeautifulSoup(html,'html.parser')  trs=soup.find_all('tr')  row=0  col=0  for tr in trs:  	style=tr.get('style')  	tds=tr.find_all('td')  	td=[x for x in tds]  	name=td[1].text.strip()  	hex=td[2].text.strip()  	table.write(row,col,name)  	table.write(row,col+1,hex)  	table.write(row,col+2,style)  	row=row+1  	col=0  data.save('MADE.xls')

PS:本来用的是XLWD这个模块,但是在测试写入到单元格时候不知道为什么,写进去立刻读能读出来数据,但是再写数据就没了,,,,也就没怎么看了。直接用了XLWT。但是他需要每次都是新建一个EXCEL然后新建一个sheet,并不难打开已经存在的excel。。。。。。。好像有办法解决,,,后面有需要再看吧。

附一个打开修改已存在excel的办法

http://www.360doc.com/content/13/1119/16/11029609_330538996.shtml

再附一个xlwd的高级用法,包括修改字体设置格式等

http://www.xuebuyuan.com/1568560.html

这里面有合并单元格的操作

http://www.jb51.net/article/60510.htm