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绘制图表前,我们需要先安装两个库文件numpy和matplotlib。Numpy是Python开源的数值计算扩展,可用来存
- 如何自动下载所有依赖包?大部分情况下大家下载 Go 项目都是使用go get命令,它除了会下载指定的项目代码,还会去下载这个项目所依赖的所有
- 0. 简介传统的并发编程模型是基于线程和共享内存的同步访问控制的,共享数据受锁的保护,线程将争夺这些锁以访问数据。通常而言,使用线程安全的数
- 在软件开发过程中经常会遇到数据库升迁的问题,原因比较多,如acsess访问速度比sql server慢、删除数据记录后access会留下空档
- 数字序号① ①② ②③ &
- PyGame 是专为游戏开发而设计的 Python 库。PyGame 建立在SDL库之上,因此它提供了用 Python 开发游戏的全部功能。
- 1.后台action产生json数据。List blackList = blackService.getBlackInfoList(mobi
- Item Pipeline简介Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰、验证和存储数据。当页面被蜘蛛
- 本文实例讲述了Go语言模拟while语句实现无限循环的方法。分享给大家供大家参考。具体实现方法如下:这段代码把for语句当成C语言里的whi
- js获取日期函数//获取当前时间日期function CurentTime(){ var now = new Date(); &
- 这几天有一台MySQL数据库服务器出现了频繁的掉线情况,通过排查,并没有排查出哪个网站被攻击,百思不得其解中的时候,群里有个朋友说是因为微软
- 组件值校验,即在组件值变化时判断是否满足校验逻辑,若不满足校验逻辑,可以拿到校验错误信息进行错误提示或其他逻辑处理。声明 valueVali
- 目录Python协程及asyncio基础知识定义协程函数及执行方法的演变创建协程任务的演变获取协程任务执行结果通过asyncio.gathe
- 找到build文件夹下面的webpack.base.conf.js文件。然后打开该文件,找到图下这段代码,把他注释掉。注释掉之后,再进行子页
- 1、Python 条件语句Python 条件语句是通过一条或多条语句的执行结果来决定执行的代码块。Python 编程中 if 语句用于控制程
- 完整代码如下:import requestsfrom lxml import etreeimport randomimport osfrom
- 目录1.程序结构2.选择语句2.1最简单的if语句2.2.if …… else 语句2.3.if…elif…else语句2.4 if 语句的
- 首先要了解为什么用连接池,连接池能为你解决什么问题连接池主要的作用:1、减少与数据服务器建立TCP连接三次握手及连接关闭四次挥手的开销,从而
- WebDriver内置了测试中捕获屏幕并保存的方法。示例脚本:(1)save_screenshot(filename):保存屏幕截图from
- 用过mac的朋友都反映很好用,不仅美观,性能好,关键是他的系统底层对于开发人员来说,无疑就是一个最大的好处,用习惯linux的人就知道mac