【发布时间】:2015-08-23 15:41:47
【问题描述】:
我正在尝试解析几千个 html 文件并将变量转储到 csv 文件(excel 电子表格)中。我遇到了几个障碍,但第一个是这样的:我无法让它正确解析文件。下面是一个简单的解释,python代码和回溯信息。
使用 Python 和 Sublime 解析 html 文件,我遇到了几个错误。什么是工作:它运行良好,直到if '.html' in file:。它不执行该循环。它将遍历print allFiles 就好了。它还创建 csv 文件并创建标题(虽然不在单独的列中,但我可以稍后再询问)。
似乎问题出在 if tree = ET.parse(HTML_PATH+"/"+file) 部分。我已经用几种不同的方式编写了这个(例如,没有“/”和/或“文件”)——到目前为止,我还没有解决这个问题。
如果我可以提供更多信息,或者如果有人可以指导我查看其他文档,我们将不胜感激。到目前为止,我还没有找到任何可以解决这个问题的东西。
非常感谢您的想法。
//C
# Parses out data from crawled html files under "html files"
# and places the output in output.csv.
import xml.etree.ElementTree as ET
import csv, codecs, os
from cStringIO import StringIO
# Note: you need to download and install this..
import unicodecsv
# TODO: make into command line params (instead of constant)
CSV_FILE='output.csv'
HTML_PATH='/Users/C/data/Folder_NS'
f = open(CSV_FILE, 'wb')
w = unicodecsv.writer(f, encoding='utf-8', delimiter=';')
w.writerow(['file', 'category', 'about', 'title', 'subtitle', 'date', 'bodyarticle'])
# redundant declarations:
category=''
about=''
title=''
subtitle=''
date=''
bodyarticle=''
print "headers created"
allFiles = os.listdir(HTML_PATH)
#with open(CSV_FILE, 'wb') as csvfile:
print "all defined"
for file in allFiles:
#print allFiles
if '.html' in file:
print "in html loop"
tree = ET.parse(HTML_PATH+"/"+file)
print '===================='
print 'Parsing file: '+file
print '===================='
for node in tree.iter():
print "tbody"
# The tbody attribute spells it all (or does it):
name = node.attrib.get('/html/body/center/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/font')
# Check common header stuff
if name=='/html/body/center/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/font':
#print ' ------------------'
#print ' Category:'
category=node.text
print "category"
f.close()
追溯:
文件“/Users/C/data/Folder_NS/data_parse.py”,第 34 行,在 树 = ET.parse(HTML_PATH+"/"+file) 解析中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第 1182 行 tree.parse(源,解析器) 解析中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第 656 行 parser.feed(数据) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第 1642 行,在提要中 self._raiseerror(v) _raiseerror 中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第 1506 行 提出错误 xml.etree.ElementTree.ParseError:标签不匹配:第 63 行,第 2 列
【问题讨论】:
-
你试过“\”还是“\\”?
-
@ybdesire 是的,我做到了。这是行不通的。不过还是谢谢你的建议。
标签: python html parsing sublimetext2