我在这个问题上苦苦挣扎了一段时间。这是我需要从中提取Annual div
而不是Annual Div yield
的表。
<table class="horizontalTable col1of3 lastCol">
<tbody>
<tr class="first">
<th>Annual div <span class="sub">(TTM)</span></th>
<td>5.49 <span class="currencyCode">GBX</span></td>
</tr>
<tr>
<th>Annual div yield <span class="sub">(TTM)</span></th>
<td>6.04%</td>
</tr>
<tr>
<th>Div ex-date</th>
<td><span class="nowrap">Sep 25 2013</span></td>
</tr>
<tr class="last">
<th>Div pay-date</th>
<td><span class="nowrap">Nov 22 2013</span></td>
</tr>
</tbody>
</table>
我写了这个XPath查询,但是它同时带了
Annual div
和Annual div yield
Annual_div = sel.xpath('//table[contains(@class, "horizontalTable col1of3")]/tbody/tr[th[contains(.,"Annual div")]]').extract()
结果:
<tr class="first"><th>Annual div <span class="sub">(TTM)</span></th><td>5.49 <span class="currencyCode">GBX</span></td></tr>', u'<tr><th>Annual div yield <span class="sub">(TTM)</span></th><td>5.83%</td></tr>
当我在精确文本上写匹配时,结果不会产生任何结果:
Annual_div = sel.xpath('//table[contains(@class, "horizontalTable col1of3")]/tbody/tr[th[text()="Annual div"]]').extract()
似乎与跨度(TTM)有关,我不确定如何将两个年级(TTM)串联起来以得出精确匹配。
请帮我。
问候
最佳答案
要通过完全匹配进行比较,您最后缺少空格。这应该工作:
//table[contains(@class, "horizontalTable col1of3")]/tbody/tr[th/text() = "Annual div "]]
但是,如果要删除前导空格和尾随空格,可以使用
nornmalize-space()
,如下所示://table[contains(@class, "horizontalTable col1of3")]/tbody/tr[normalize-space(th/text()) = 'Annual div']
关于python-2.7 - 如何串连XPath,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22894572/