python读取html中指定元素生成excle文件示例

时间:2021-04-08 19:51:11 

Python2.7编写的读取html中指定元素,并生成excle文件


#coding=gbk
import string
import codecs
import os,time
import xlwt
import xlrd
from bs4 import BeautifulSoup
from xlrd import open_workbook

class LogMsg:
        def __init__(self,logfile,Level=0):
                try:
                        import logging
                        #self.logger = None
                        self.logger = logging.getLogger()
                        self.hdlr = logging.FileHandler(logfile)
                        formatter = logging.Formatter("[%(asctime)s]: %(message)s","%Y%m%d %H:%M:%S")
                        self.hdlr.setFormatter(formatter)
                        self.logger.addHandler(self.hdlr)
                        #logger.setLevel()
                        if Level == 10:
                                self.logger.setLevel(logging.DEBUG)
                        elif Level == 20:
                                self.logger.setLevel(logging.INFO)
                        elif Level == 30:
                                self.logger.setLevel(logging.WARNING)
                        elif Level == 40:
                                self.logger.setLevel(logging.ERROR)
                        elif Level == 50:
                                self.logger.setLevel(logging.CRITICAL)
                        else:
                                self.logger.setLevel(logging.NOTSET)
                except:
                        print "log init error!"
                        exit(1)

        def output(self,logInfo):
                Level = self.logger.getEffectiveLevel()
                try:
                        if Level == 10:
                                self.logger.debug(logInfo)
                        elif Level == 20:
                                self.logger.info(logInfo)
                        elif Level == 30:
                                self.logger.warning(logInfo)
                        elif Level == 40:
                                self.logger.error(logInfo)
                        elif Level == 50:
                                self.logger.critical(logInfo)
                        else:
                                self.logger.info(logInfo)
                except:
                        print "log output error!"
                        exit(1)

        def close(self):
                try:
                #logging.shutdown([self.hdlr])
                        self.logger.removeHandler(self.hdlr)
                except:
                        print "log closed error!"
                        exit(1)

Logtime = time.strftime("%Y%m%d%H%M%S",time.localtime())
logFileTime = time.strftime("%Y%m%d",time.localtime())
Logfile = '/data/pyExample/logs/htmlparser_%s.log' % logFileTime
log = LogMsg(Logfile,20)


DATAPATH = '/data/pyExample/'
XLSname = 'dangjian_'+Logtime+'.xls'


if __name__ == '__main__':
   

    wbk = xlwt.Workbook(encoding = 'gbk')
    sheet = wbk.add_sheet('基本内容导入模板')
    sheet.write(0,0,'内容类型 ')
    sheet.write(0,1,'栏目名称')
    sheet.write(0,2,'栏目编号')
    sheet.write(0,3,'内容名称')
    sheet.write(0,4,'时长')
    sheet.write(0,5,'关键字')
    sheet.write(0,6,'看点')
    sheet.write(0,7,'作者')
    sheet.write(0,8,'来源')
    sheet.write(0,9,'子内容1')
    sheet.write(0,10,'子内容2')
    xlsContent = []  
    files = os.listdir(DATAPATH)
    k = 0
    for f in files: 
        if os.path.splitext(f)[1] == '.html':
            content=[]
            log.output('当前文件:'+f)
            htmlFile =codecs.open(DATAPATH+f,'r','gbk')
            lines = htmlFile.readlines()
            if not lines:
                log.output ('not line')
            for line in lines:
                if line.strip()=='\n':
                    log.output('该处是空行')
                else:
                    line = line.replace(' ','')
                    soup  = BeautifulSoup(line)
                    for tdd in soup.findAll('td'): 
                        #print tdd.text.encode("gbk")
                        content.append(tdd.text.encode("gbk"))      
                #print line.encode('gbk')
            htmlFile.close()   
            for i in content:
                print content.index(i),',',i
                log.output(i)
                log.output(content.index(i))
            print '----------------------------------------'
           

            folderName =  content[6]
            contentName=  content[4]      
            duration =    filter(str.isdigit, content[16])
            int_duration = string.atoi(duration)*60
            str_duration = "%i"%int_duration
            keyWord =     content[6]
            desciption =  content[36]
            videoName_1 = content[10]
            print folderName
            print contentName
            print str_duration
            print keyWord
            print desciption
            print videoName_1
            log.output('输出xls数据:'+','+folderName+',,'+contentName+','+str_duration+','+keyWord+','+desciption+',管理员,华数编辑,'+videoName_1+',,')
            print k           
            sheet.write(k+1,0,'')
            sheet.write(k+1,1,folderName)
            sheet.write(k+1,2,'')
            sheet.write(k+1,3,contentName)
            sheet.write(k+1,4,str_duration)
            sheet.write(k+1,5,keyWord)
            sheet.write(k+1,6,desciption)
            sheet.write(k+1,7,'管理员')
            sheet.write(k+1,8,'华数编辑')
            sheet.write(k+1,9,videoName_1)
            sheet.write(k+1,10,'')
            k+=1

    wbk.save(DATAPATH + XLSname)       

    print '=========================================' 

标签:python,html,excle
0
投稿

猜你喜欢

  • python GUI库图形界面开发之PyQt5中QMainWindow, QWidget以及QDialog的区别和选择

    2022-04-22 01:39:50
  • asp如何让用户也能修改密码?

    2010-05-13 16:41:00
  • python 基于opencv实现图像增强

    2023-03-20 21:04:32
  • 教你如何使用Python开发一个钉钉群应答机器人

    2023-08-03 17:44:16
  • sqlserver 临时表 Vs 表变量 详细介绍

    2011-11-03 17:34:10
  • 如何把数组转换成字符串?

    2009-11-06 13:49:00
  • Python 模块EasyGui详细介绍

    2022-04-27 22:55:39
  • Go单元测试对GORM进行Mock测试

    2023-07-20 17:38:53
  • 完美的渐变透明效果,支持Firefox

    2008-06-18 18:18:00
  • 解决SQL Server的“此数据库没有有效所有者”问题

    2011-12-14 18:29:35
  • 再读《你是一个职业的页面重构工作者吗?》

    2009-02-11 12:22:00
  • Django发送html邮件的方法

    2021-04-06 13:22:52
  • Python模块pexpect安装及使用流程

    2023-04-19 05:41:29
  • Python多线程下载文件的方法

    2021-12-26 05:21:32
  • js 实现数值的千分位及保存小数方法(推荐)

    2023-08-17 01:13:11
  • 你会使用python爬虫抓取弹幕吗

    2021-04-28 03:06:50
  • python opencv 图像拼接的实现方法

    2021-06-21 19:11:51
  • php SQL防注入代码集合

    2023-11-18 03:58:34
  • asp函数InstrRev()介绍及获取文件名例子

    2007-11-19 19:01:00
  • python实现Nao机器人的单目测距

    2021-04-09 16:37:10
  • asp之家 网络编程 m.aspxhome.com