Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用ElementTree xpath解析html文件(到csv)时遇到问题_Python_Html_Csv_Xpath - Fatal编程技术网

在python中使用ElementTree xpath解析html文件(到csv)时遇到问题

在python中使用ElementTree xpath解析html文件(到csv)时遇到问题,python,html,csv,xpath,Python,Html,Csv,Xpath,我试图解析几千个html文件,并将变量转储到csv文件(excel电子表格)中。我遇到了几个障碍——第一个是(谢天谢地)几天前在这里解决的。(希望如此)最后的障碍是:我无法让它使用xpath正确解析文件。下面是一个简短的解释,python代码和html代码的示例 问题从这里开始: for node in tree.iter(): name = node.attrib.get('/html/body/table/tbody/tr/td/table/tbody/tr[3]/t

我试图解析几千个html文件,并将变量转储到csv文件(excel电子表格)中。我遇到了几个障碍——第一个是(谢天谢地)几天前在这里解决的。(希望如此)最后的障碍是:我无法让它使用xpath正确解析文件。下面是一个简短的解释,python代码和html代码的示例

问题从这里开始:

for node in tree.iter():
            name = node.attrib.get('/html/body/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/p/span')
            if category =='/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':
            category=node.text
它运行,但不解析。我没有收到任何回溯错误

我想我误解了ElementTree解析的逻辑

有几个相同的头——因此很难找到唯一的id/头。以下是html的一个示例:

<span class="s1">Business: Give Back to the Community and Save Money 
on Equipment, Technology, Promotional Products, and Market<span 
class="Apple-converted-space">&nbsp;</span></span>
我想从这个跨度(以及其他跨度)中提取文本,并将其放入excel电子表格中

您可以看到一个类似页面的示例

无论如何,因为许多跨距/头都不是唯一标识的,所以我认为应该使用xpath。然而,我还没有弄清楚如何将xpath命令成功地用于ElementTree。在搜索文档时,我找不到这个问题的答案(以及逻辑)。我已经阅读了这个网站,也阅读了这个网站,但还没有找到有效的方法

到目前为止,代码很好地遍历了所有文件(在dropbox中)。它还创建csv文件并创建标题(虽然不在单独的列中,只作为一行用分号分隔,但这应该很容易修复)

总之,我希望它解析每个文件(网页)中不同行的文本,并将其转储到excel文件中

如有任何意见,将不胜感激

python代码:

import xml.etree.ElementTree as ET
import csv, codecs, os
from cStringIO import StringIO
# Note: you need to download and install this..
import unicodecsv
import lxml.html
# 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 = lxml.html.parse(HTML_PATH+"/"+file)
        print '===================='
        print 'Parsing file: '+file
        print '===================='
        for node in tree.iter():
            name = node.attrib.get('/html/body/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/p/span')

            if category =='/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 'Category:'
            category=node.text

f.close()
2015年6月14日(最新变更);我刚换了这一部分

        for node in tree.iter():
            name = node.attrib.get('/html/body/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/p/span')

            if category =='/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 'Category:'
            category=node.text
为此:

    for node in tree.iter():
            row = dict.fromkeys(cols)
            Category_name = tree.xpath('/html/body/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/table/tbody/tr[1]/td[1]/p/span')
            row['category'] = Category_name[0].text_content().encode('utf-8')
它仍然运行,但不解析

尝试以下代码:

from lxml import etree 
import requests
from StringIO import StringIO

data = requests.get('http://www.usprwire.com/Detailed/Banking_Finance_Investment/Confused.com_reveals_that_Life_Insurance_is_more_than_a_form_of_future_protection_284764.shtml').content
parser = etree.HTMLParser()
root = etree.parse(StringIO(data), parser)
category = root.xpath('//table/td/font/text()')
print category[0]
它使用
请求
库下载页面的
html
代码。你可以选择任何适合你需要的方法。重要的部分是
xpath
,它搜索任何
,后跟
,并返回一个包含两个元素的列表。第二个是空白字符,第一个包含文本

运行它,只产生你想要的句子:

Banking, Finance & Investment: Confused.com reveals that Life Insurance is more than a form of future protection

为什么不尝试使用
tree.xpath()
函数呢。这里是文档:@Birei感谢您的评论。我已经从那个文档中尝试了一些东西。最近我修改了代码——我似乎无法将这些修改放在这个注释中,所以我编辑了上面的问题。它仍然没有解析。你能提供一个
html
页面,我们可以在那里测试你的
xpath
?@Birei它在上面的文本中提供(“你可以看到一个类似页面的示例”),请让我知道我是否可以提供进一步的详细信息,或者以其他形式提供详细信息。好的。我使用该页面测试您的
xpath
,但没有返回任何内容。您要查找的类别在哪里?谢谢@Birei。但是如果我想从一个(单个)文件中删除文本,那么您发布的代码(尤其是http:…)将非常有用网站。发布该特定链接是为了给出我需要解析代码的文件的html代码示例。我有大约4000个。虽然xpath很有用(谢谢),但我仍然不清楚如何从这些文件中(从循环中)提取文本并将其显示在xl文件中。感谢您花时间回答这个问题。@Christine:通过这个示例,我向您展示了如何提取类别。这是您的问题。我想它不会完全适用于4000个文件,但这是您的工作,不是我的。您继承了该代码吗?如果您不确定,请y您应该首先尝试学习Python,然后思考解决问题的正确方法。正如我所说的,非常感谢您对代码xpath部分的帮助。事实上,我正在学习Python。再次感谢您抽出时间。
Banking, Finance & Investment: Confused.com reveals that Life Insurance is more than a form of future protection