python 操作csv

来源:互联网 发布:linux安装.xz 编辑:程序博客网 时间:2024/05/29 17:55

爬取网页的时候,有时候需要爬去表格里面的数据,这时候可以考虑吧他存放到csv格式的文件里面去,下面是Python 操作csv 模板的一些 基本操作

from urllib.request import urlopenfrom bs4 import BeautifulSoupimport csvhtml = urlopen('http://en.wikipedia.org/wiki/Comparison_of_text_editors')bs4 = BeautifulSoup(html,'xml')table = bs4.findAll("table")[0]rows = table.findAll('tr')csvFile = open("./editors.csv", 'wt', encoding='utf-8')writer = csv.writer(csvFile)    #这是一个写入对象try:    for row in rows:        csvRow = []   #用列表的话  会打逗号,然后在写里面去        for cell in row.findAll(['td','th']):            csvRow.append(cell.get_text())        writer.writerow(csvRow) #这部分其实书上应该是写错了的   finally:    csvFile.close()

(上述代码来自python数据采集一书)

原创粉丝点击