您的位置:首页 > 编程语言 > Python开发

Python爬虫爬数据写入到EXCEL中

2016-03-16 11:55 489 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel Python 写到