23ewrw 发表于 2016-3-17 08:58:47

Python爬虫爬数据写入到EXCEL中

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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=
    name=td.text.strip()
    hex=td.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。。。。。。。好像有办法解决,,,后面有需要再看吧。

页: [1]
查看完整版本: Python爬虫爬数据写入到EXCEL中