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 '========================================='
猜你喜欢
- fmtfmt是go语言中的格式化输入输出库,其中主要分为两个部分,分别是输出部分和输入部分。输出PrintPrint函数的主要功能是输出,和
- 本文通过实例解析了 SQL Server 数据库扩展存储过程,实现远程备份与恢复的方法和步骤实例说明: 环境:win2k+sqlserver
- 详细代码见仓库github地址:github.com/nerkeler/account重要提示程序默认密码:password密钥位置:./r
- 本文实例讲述了python中for语句简单遍历数据的方法。分享给大家供大家参考。具体如下:for name in ["kak&qu
- Appium在前文的讲解中,我们学会了如何安装Appium,以及一些基础获取App元素内容的方式。但认真看过前文的读者,肯定在博主获取元素的
- 如果你想让你的IIS支持wml,做个wap网站,只需作小小的改变就行了.虽然目前支持wml的虚拟主机极少,但是自己在本机上玩玩也好的.首先在
- 功能:创建两个滑动条来分别控制高斯核的size和σσ的大小,这个程序是在阈值分割的那个程序上改动的。阈值分割程序在这 注意:由于σ=0σ=0
- 废话不多说了,直接给大家贴js代码了,具体代码如下所示:<!DOCTYPE html><html><head&
- python pycharm中使用opencv时,没有代码自动补全提示解决方案有2种今天工作时突然发现,在写OPENCV相关代码时,没有自动
- 当你的查询相对简单的时候,每次从头开始创建SQL语句也不费什么工夫,不过,复杂的查询就不同了,每次都从头来会产生很多开发错误。因此,一旦让S
- <?php $fp = fopen("http://www.***.com/**
- 看如下asp代码:<%@ codepage="65001" %><!-- 
- 最近一周每天早上起来第一件事,就是打开新闻软件看疫情相关的新闻。了解下自己和亲友所在城市的确诊人数,但纯数字还是缺乏一个直观的概念。那我们来
- 一,PHP脚本与动态页面。 PHP脚本是一种服务器端脚本程序,可通过嵌入等方 法与HTML文件混合,也可以类,函数封
- 作者:Henny Swan / co-lead of WaSP ILG译者:JunChen / member of WaSP ILG原文:h
- 思考一个问题:怎么实现在第一次检索的基础上进行二次检索?通常,我们的做法是第一次检索时保存检索条件,在第二次行检索时组合两次检索条件对数据库
- 本文实例讲述了Golang正整数指定规则排序算法问题。分享给大家供大家参考,具体如下:给定字符串内有很多正整数,要求对这些正整数进行排序,然
- 问题:在论坛发表回复时出现“The table is full”的提示,字面意义上是数据表已满的意思。因为很少有开发者遭遇单一表超过4G的情
- 经过一个阶段的asp学习,下面我们结合所学过的内容建立一个最简单的聊天室,虽然很简单,但是大家可以通过他来掌握一个聊天室建立的基本过程,并且
- 在网上查阅资料,发现很少用Python进行高斯函数的三维显示绘图的,原因可能是其图形显示太过怪异,没有MATLAB精细和直观。回顾一下二维高