批量html转text

本文介绍了一种使用Python和Internet Explorer Application对象模型批量将HTML文件转换为纯文本的方法。通过解析HTML并提取文本内容,该工具能有效处理大量HTML文件,尽管在某些情况下可能遇到与资源管理器交互的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

批量html转text

(转载请注明来源于金庆的专栏)

原来的代码是参考“Recipe 12.11. Using MSHTML to Parse XML or HTML”,利用htmlfile提取文本。
将当前目录下的所有html文件转换为text文件。

defextractHtmlFile(htmlFilePath):
'''Extracthtmltextandsavetotextfile.
'''
htmlData
=file(htmlFilePath,'r').read()
importwin32com.client
html
=win32com.client.Dispatch('htmlfile')
html.writeln(htmlData)
text
=html.body.innerText.encode('gbk','ignore')
...

但是发现MSHTML解析文件可能会出错,造成文本提取失败。

jigloo经过对10W+个html文件的测试,得出结论,htmlfile的容错比InternetExplorer.Application要差很多。
原文见:http://groups.google.com/group/python-cn/msg/c9221764bcafbc21
他的代码大致如下,IE使用稍烦:

#!/usr/bin/envpython

importsys,os,re,codecs
importtime
importwin32com.client

classhtmlfile:
def__init__(self):
self.
__ie=win32com.client.Dispatch('InternetExplorer.Application')
self.
__ie.Silent=True
self.
__filename=''
self.
__document=None

def__del__(self):
self.
__ie.Quit()

def__getdocument(self,filename):
filename
=os.path.abspath(filename)
ifself.__filename!=filename:
self.
__filename=filename
self.
__ie.Navigate2(filename)
self.
__ie.Document.close()
whileself.__ie.Document.BodyisNone:
time.sleep(
0.1)
self.
__document=self.__ie.Document
returnself.__document
defgettext(self,filename):
returnself.__getdocument(filename).Body.innerText
defgettitle(self,filename):
returnself.__getdocument(filename).title

defformattextpath(dir,htmlfile,htmltitle):
'''Formatthetextfilepathandreturn.
'''
fname
=htmltitle[:6]
fname
=re.sub(r'(/|/|:|*|?|<|>|||")','-',fname)
fname
=fname+'_'+os.path.splitext(htmlfile)[0]+'.txt'
returnos.path.join(root,fname)

if__name__=='__main__':
hf
=htmlfile()
forroot,dirs,namesinos.walk(u'.'):
fornameinnames:
ifname.endswith('htm')orname.endswith('html'):
htmlpath
=os.path.join(root,name)
textpath
=formattextpath(root,name,hf.gettitle(htmlpath))
printhtmlpath,'->',textpath
file(textpath,
'wb').write(hf.gettext(htmlpath).encode('mbcs'))
#Endofif.
#Endofforname.
#Endofforroot.
delhf
#Endofif.

对于我的简单任务,这就足够了。

有一个问题,如果有资源管理器打开着,运行这段代码会关闭资源管理器,并出错退出。比较奇怪,但应该不难解决,可能是IE控件的使用上还有问题。

self.__ie.Document.close()
File "C:/Python25/Lib/site-packages/win32com/client/dynamic.py", line 496, in
__getattr__
raise AttributeError, "%s.%s" % (self._username_, attr)
AttributeError: Document.close


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值