使用Python Xpath将数据提取到csv文件

时间:2017-02-12 01:51:55

标签: python xpath lxml

感谢Python Xpath的帮助。我有以下xml代码。 目前,我正在使用python并逐行阅读,然后尝试提取它。但是我意识到这些表是1000行长,并且逐行使用来读取它并将逻辑放在我身上。

我想从xml代码中提取这些数据并输入到csv文件中。

如何使用Xpath来完成它?

示例xml代码:

<thead>
    <tr>
        <th class="section" data-bind="text: name">Ratios</th>
        <!-- ko foreach : $parent.dataPoints -->
            <th>
                <span data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod">FY2013</span>
                <br>
                <span data-bind="text: periodDate, format: 'date'">30/Jun/2013</span>
            </th>

            <th>
                <span data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod">FY2014</span>
                <br>
                <span data-bind="text: periodDate, format: 'date'">30/Jun/2014</span>
            </th>

            <th>
                <span data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod">FY2015</span>
                <br>
                <span data-bind="text: periodDate, format: 'date'">30/Jun/2015</span>
            </th>

            <th>
                <span data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod">FY2016</span>
                <br>
                <span data-bind="text: periodDate, format: 'date'">30/Jun/2016</span>
            </th>

            <th>
                <span data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod">LTM Ending</span>
                <br>
                <span data-bind="text: periodDate, format: 'date'">31/Dec/2016</span>
            </th>
        <!-- /ko -->
        <th class="uncheck" data-bind="visible: $root.series().length > 0" style="display: none;">&nbsp;</th>
    </tr>
</thead>
<tbody>
    <!-- ko foreach : dataPoints -->
        <tr data-bind="css: { 'odd': ($index() % 2 == 0) }" class="odd">
            <td class="checkbox left">
                <div class="trigger" data-bind="attr: { 'data-name': property, 'data-group': group }, click: function(data, event) { $root.handleClick($root, data, event); }" data-name="returnAssets" data-group="ratio">
                    <span class="name" data-bind="text: name">Return on Assets</span>
                    <span data-bind="visible: $data.hasOwnProperty('glossaryTerm')">
                        <img src="img/info.png" alt="" data-bind="tooltip: $data.hasOwnProperty('glossaryTerm') ? glossaryTerm : null" tooltip-copy="Return on Assets is a measure of company profitability relative to total assets. It is calculated by dividing tax-effective EBIT (Earnings before Interest and Tax) by Average Total Assets over a 12-months period." class="tooltip-item">
                    </span>
                </div>
                <input type="checkbox">
            </td>
            <!-- ko foreach : $root.dataPoints -->
                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="14.6931" data-name="returnAssets">14.693</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="13.5242" data-name="returnAssets">13.524</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="14.5923" data-name="returnAssets">14.592</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="13.0935" data-name="returnAssets">13.094</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="15.4657" data-name="returnAssets">15.466</td>
            <!-- /ko -->
            <td class="uncheck" data-bind="visible: $root.series().length > 0, click: function(data, event) { $root.handleClick($root, data, event); }" style="display: none;">
                <span data-bind="visible: $root.canUncheck($root, property)" style="display: none;">[UNCHART]</span>
            </td>
        </tr>

        <tr data-bind="css: { 'odd': ($index() % 2 == 0) }">
            <td class="checkbox left">
                <div class="trigger" data-bind="attr: { 'data-name': property, 'data-group': group }, click: function(data, event) { $root.handleClick($root, data, event); }" data-name="returnCapital" data-group="ratio">
                    <span class="name" data-bind="text: name">Return on Capital</span>
                    <span data-bind="visible: $data.hasOwnProperty('glossaryTerm')">
                        <img src="img/info.png" alt="" data-bind="tooltip: $data.hasOwnProperty('glossaryTerm') ? glossaryTerm : null" tooltip-copy="Return on Capital is a measure of company profitability relative to total capitals. It is calculated by dividing tax-effective EBIT (Earnings before Interest and Tax) by Average Total Capital over a 12-months period." class="tooltip-item">
                    </span>
                </div>
                <input type="checkbox">
            </td>
            <!-- ko foreach : $root.dataPoints -->
                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="30.0726" data-name="returnCapital">30.073</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="25.6597" data-name="returnCapital">25.66</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="26.4617" data-name="returnCapital">26.462</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="26.0215" data-name="returnCapital">26.021</td>

                <td data-bind="text: $data.hasOwnProperty($parent.property) &amp;&amp; $data[$parent.property] != null? $data[$parent.property] : '-', formatNonZeroValue: 'number', attr: { 'data-value': $data.hasOwnProperty($parent.property) ? $data[$parent.property] : null, 'data-name': $parent.property }" data-value="27.67" data-name="returnCapital">27.67</td>
            <!-- /ko -->
            <td class="uncheck" data-bind="visible: $root.series().length > 0, click: function(data, event) { $root.handleClick($root, data, event); }" style="display: none;">
                <span data-bind="visible: $root.canUncheck($root, property)" style="display: none;">[UNCHART]</span>
            </td>
        </tr>
</tbody>

将输出的样本输出为excel作为表格报告

enter image description here

2 个答案:

答案 0 :(得分:1)

我之前必须解决这个问题,并为https://pypi.python.org/pypi/messytables编写了一个HTML解析器,以获得对表的编程访问。

您应该将lxml.html用于html,而不是lxml.etree。界面大致相同。

基本上,您应该遍历每个table元素以提取行(tr),每个tr以提取tdth,并获取他们每个人的文字。我不会过度指定你想要获得的元素。

如果您遇到问题然后必须重新构建您获​​得的数据,您可能会发现https://github.com/sensiblecodeio/xypath有用。 [免责声明:我写了大部分内容]

答案 1 :(得分:0)

是的,可以用lxml.etree解析html。但确切的代码取决于文件中使用的命名空间。 假设你有

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>

在文件的开头,此代码有效:

from lxml import etree

parser = etree.XMLParser(attribute_defaults=False, load_dtd=True,   resolve_entities=True,remove_comments=False, ns_clean=True, recover=True)
file = "C:\\test1.html" # your filename here
data = etree.parse(file, parser=parser)
headers = etree.XPath('''//h:span [@data-bind="text: absPeriod.indexOf('LTM') != -1 ? 'LTM Ending' : absPeriod"] ''', namespaces={'h':"http://www.w3.org/1999/xhtml"})
dates = etree.XPath('''//h:span [@data-bind="text: periodDate, format: 'date'"] ''', namespaces={'h':"http://www.w3.org/1999/xhtml"})
assets = etree.XPath('''//h:td [@data-name="returnAssets"]''', namespaces={'h':"http://www.w3.org/1999/xhtml"})
capitals = etree.XPath('''//h:td [@data-name="returnCapital"]''', namespaces={'h':"http://www.w3.org/1999/xhtml"})
header = [x.text for x in headers(data)]
date = [x.text for x in dates(data)]
asset = [x.text for x in assets(data)]
capital = [x.text for x in capitals(data)]
print(header)
print(date)
print(asset)
print(capital)

给你:

['FY2013', 'FY2014', 'FY2015', 'FY2016', 'LTM Ending']
['30/Jun/2013', '30/Jun/2014', '30/Jun/2015', '30/Jun/2016', '31/Dec/2016']
['14.693', '13.524', '14.592', '13.094', '15.466']
['30.073', '25.66', '26.462', '26.021', '27.67']

从这开始,您现在可以将数据放入CSV(抱歉,我不知道这一点)。