Python批量下载网页中的表格存储到CSV文件中

'''
Created on Feb 28, 2017


@author: hcq908
'''
import csv
import os
# import re
from urllib.request import urlopen
from bs4 import BeautifulSoup


if __name__ == '__main__':
    iCntTable = 0;
    html = urlopen("https://en.wikipedia.org/wiki/Comparison_of_text_editors")
    bsObj = BeautifulSoup(html, "html.parser")
    oTables = bsObj.find_all("table")#选定第一个表格
    for table in oTables:
        iCntTable  =iCntTable + 1;
        print('处理第%d个表格 \n'%iCntTable)
        #获取表格名称
        sTitleTag = table.find('caption');#标题只有一个
    #     sMatchText = re.compile(r'<[^>]+>', re.S)
    #     sTextRemain = sMatchText.sub('', sTitleTag)
        sTitleName=sTitleTag.get_text()+'.csv';
        
        #路劲不存在是需要新建
        sDir = 'files';
        if not os.path.exists(sDir):
            os.mkdir(sDir)
        sCSV_Path = os.path.join(sDir,sTitleName);    
        rows = table.find_all("tr")#tr为每一行的标签
        
        with open(sCSV_Path, 'wt', newline='', encoding='utf-8') as csvFile: #创建可写文件
            writer = csv.writer(csvFile)
            for row in rows:#先按行处理
                csvRow = []#创建列表存储每行数据
                for cell in row.find_all(['td', 'th']):#再按列处理,搜索一行中每格的内容,td或th都可以
                    csvRow.append(cell.get_text())#将每格中的数据追加到列表
                writer.writerow(csvRow)#写入一行
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值