我有一个类似于以下的html文档:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
<div id="Symbols" class="cb">
<table class="quotes">
<tr><th>Code</th><th>Name</th>
<th style="text-align:right;">High</th>
<th style="text-align:right;">Low</th>
</tr>
<tr class="ro" onclick="location.href='/xyz.com/A.htm';" style="color:red;">
<td><a href="/xyz.com/A.htm" title="Display,A">A</a></td>
<td>A Inc.</td>
<td align="right">45.44</td>
<td align="right">44.26</td>
<tr class="re" onclick="location.href='/xyz.com/B.htm';" style="color:red;">
<td><a href="/xyz.com/B.htm" title="Display,B">B</a></td>
<td>B Inc.</td>
<td align="right">18.29</td>
<td align="right">17.92</td>
</div></html>
Run Code Online (Sandbox Code Playgroud)
我需要code/name/high/low从表中提取信息.
我使用了Stack Over Flow中类似示例中的以下代码:
#############################
import urllib2
from lxml import html, etree
webpg = urllib2.urlopen(http://www.eoddata.com/stocklist/NYSE/A.htm).read()
table = html.fromstring(webpg)
for row in table.xpath('//table[@class="quotes"]/tbody/tr'):
for column in row.xpath('./th[position()>0]/text() | ./td[position()=1]/a/text() | ./td[position()>1]/text()'):
print column.strip(),
print
#############################
Run Code Online (Sandbox Code Playgroud)
我没有得到任何输出.我必须将第一个循环xpath更改table.xpath('//tr') …
我正在使用CPAN XML::LibXML模块处理下面的XML数据.我需要确定每个元素是否都有子元素.搜索我无法找到任何这样的例子.
<A>
<ts>2012</ts>
<T>M1</T>
<T>M2</T>
<B>
<id>PC</id>
<r>10</r>
<r>30</r>
</B>
</A>
Run Code Online (Sandbox Code Playgroud)
这是我写的Perl代码
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my ($x,$elname,$haschild)= ();
my $parser = XML::LibXML->new();
my $npo = $parser->parse_file("test.xml");
my $rootel = $npo -> getDocumentElement();
$elname = $rootel -> nodeName();
print "Root name=$elname\n";
foreach $x ($rootel->childNodes) {
$elname = $x -> nodeName();
$haschild = $x->hasChildNodes;
print "Child name = $elname and has child = $haschild.\n" unless ($elname =~ /#text/i);
}
Run Code Online (Sandbox Code Playgroud)
虽然我过去childNodes经历过每个节点,但我找不到一种简单的方法来确定节点是否有孩子.
我希望在遍历所有节点之后得到结果:
A: Has children …Run Code Online (Sandbox Code Playgroud)