Python reads the specified element in HTML to generate the Excle file example

Source: Internet
Author: User
Python2.7 writes the specified element in the HTML and generates the Excle file

Copy the Code code as follows:


#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 = =:
Self.logger.setLevel (logging. DEBUG)
Elif level = =:
Self.logger.setLevel (logging.info)
elif level = =:
Self.logger.setLevel ( Logging. WARNING)
Elif level = =:
Self.logger.setLevel (logging. ERROR)
Elif level = =:
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 (' Basic Content import template ')
Sheet.write (0,0, ' content type ')
Sheet.write (0,1, ' column name ')
Sheet.write (0,2, ' column number ')
Sheet.write (0,3, ' content name ')
Sheet.write (0,4, ' duration ')
Sheet.write (0,5, ' keywords ')
Sheet.write (0,6, ' spectacle ')
Sheet.write (0,7, ' author ')
Sheet.write (0,8, ' source ')
Sheet.write (0,9, ' sub-content 1 ')
Sheet.write (0,10, ' sub-content 2 ')
Xlscontent = []
Files = Os.listdir (DATAPATH)
K = 0
For f in Files:
If Os.path.splitext (f) [1] = = '. html ':
Content=[]
Log.output (' Current file: ' +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 (' The place is a blank line ')
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 (' Output XLS data: ' + ', ' +foldername+ ',, ' +contentname+ ', ' +str_duration+ ', ' + Keyword+ ', ' +desciption+ ', Administrator, China number editor, ' +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, ' admin ')
Sheet.write (k+1,8, ' Chinese number edit ')
Sheet.write (k+1,9,videoname_1)
Sheet.write (k+1,10, ')
K+=1

Wbk.save (DATAPATH + xlsname)

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

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.