使用Scrapy从具有多个后代的节点中截取文本

时间:2014-02-23 03:56:46

标签: python html xpath scrapy

我正在尝试使用Scrapy从HTML表中删除下面的行:

<tr bgcolor="#F3F1E6">

  <td class="htable_eng_text" align="center">
    <a href="results.asp?racedate=02/02/2014&amp;raceno=08&amp;venue=ST" class="htable_eng_text">
      368
    </a>
  </td>

  <td class="htable_eng_text" align="center">
    02/02/14
  </td>

  <td class="htable_eng_text" align="center" nowrap="">
    ST / 
    <font title="TURF">
      "Turf" / 
    </font>
    "C         "
  </td>

  <td class="htable_eng_text" align="center">
    <font class="htable_eng_rpnarrow_text">
      4
    </font>
    <font class="htable_eng_rpnarrow_text">
      &nbsp;&nbsp;4
    </font>
    <font class="htable_eng_rpnarrow_text">
      &nbsp;&nbsp;3
    </font>
    <font class="htable_eng_rpnarrow_text">
      &nbsp;&nbsp;2
    </font>
    <font class="htable_eng_rpnarrow_text">
      &nbsp;&nbsp;5
    </font>
</tr>

我希望输出为:

['368',
'02/02/14',
'ST / "Turf" / "C     "',
'4 4 3 2 5']

我当前的Xpath尝试如下:

sel.xpath('td//text()[normalize-space()]').extract()

如果文本位于<td>标记内或嵌套标记不分支(例如第一个和第二个单元格),则它可以正常工作。但是如果单元格包含多个后代(例如第三个和第四个单元格),这会导致问题,因为我的Xpath为每个后代返回一个单独的元素,但是我希望它们连接在一起。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

>>> h = '''
... <table>
... <tr bgcolor="#F3F1E6">
... ...
... </tr>
... </table>
... '''
>>>
>>> from scrapy.selector import Selector
>>> import re
>>> def normalize(xs):
...     text = ''.join(xs)
...     text = text.strip()
...     return re.sub(r'[\s\xa0]+', ' ', text)
...
>>> root = Selector(text=h, type='html')
>>> print [normalize(x.xpath('.//text()').extract()) for x in root.xpath('.//td')]
[u'368', u'02/02/14', u'ST / "Turf" / "C "', u'4 4 3 2 5']