python讀取html中指定元素生成excle文件示例
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('基本內(nèi)容導(dǎo)入模板')
sheet.write(0,0,'內(nèi)容類型 ')
sheet.write(0,1,'欄目名稱')
sheet.write(0,2,'欄目編號')
sheet.write(0,3,'內(nèi)容名稱')
sheet.write(0,4,'時長')
sheet.write(0,5,'關(guān)鍵字')
sheet.write(0,6,'看點')
sheet.write(0,7,'作者')
sheet.write(0,8,'來源')
sheet.write(0,9,'子內(nèi)容1')
sheet.write(0,10,'子內(nèi)容2')
xlsContent = []
files = os.listdir(DATAPATH)
k = 0
for f in files:
if os.path.splitext(f)[1] == '.html':
content=[]
log.output('當(dāng)前文件:'+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數(shù)據(jù):'+','+folderName+',,'+contentName+','+str_duration+','+keyWord+','+desciption+',管理員,華數(shù)編輯,'+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,'華數(shù)編輯')
sheet.write(k+1,9,videoName_1)
sheet.write(k+1,10,'')
k+=1
wbk.save(DATAPATH + XLSname)
print '========================================='
相關(guān)文章
Python變量、數(shù)據(jù)類型、數(shù)據(jù)類型轉(zhuǎn)換相關(guān)函數(shù)用法實例詳解
這篇文章主要介紹了Python變量、數(shù)據(jù)類型、數(shù)據(jù)類型轉(zhuǎn)換相關(guān)函數(shù)用法,結(jié)合實例形式詳細(xì)分析了Python變量類型、基本用法、變量類型轉(zhuǎn)換相關(guān)函數(shù)與使用技巧,需要的朋友可以參考下2020-01-01Pandas查詢數(shù)據(jù)df.query的使用
本文主要介紹了Pandas查詢數(shù)據(jù)df.query的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07淺談keras中Dropout在預(yù)測過程中是否仍要起作用
這篇文章主要介紹了淺談keras中Dropout在預(yù)測過程中是否仍要起作用,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07python可視化篇之流式數(shù)據(jù)監(jiān)控的實現(xiàn)
這篇文章主要介紹了python可視化篇之流式數(shù)據(jù)監(jiān)控的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08關(guān)于numpy中eye和identity的區(qū)別詳解
今天小編就為大家分享一篇關(guān)于numpy中eye和identity的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11python利用datetime模塊計算程序運(yùn)行時間問題
這篇文章主要介紹了python利用datetime模塊計算程序運(yùn)行時間,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02使用Python實現(xiàn)一個蔡徐坤大戰(zhàn)籃球的小游戲(推薦)
這篇文章主要介紹了用Python實現(xiàn)一個蔡徐坤大戰(zhàn)籃球的小游戲,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12Python操作使用MySQL數(shù)據(jù)庫的實例代碼
本篇文章主要介紹了Python 操作 MySQL的實例代碼,詳細(xì)介紹了Python如何連接數(shù)據(jù)庫和對數(shù)據(jù)的增刪查改,有興趣的可以了解一下2017-05-05