从lxml中的html解析日期字符串

时间:2012-06-14 13:34:52

标签: python html lxml

 s = """
      <tbody>
      <tr>
       <td style="border-bottom: none">
       <span class="graytext" style="font-weight: bold;"> Reply #3 - </span>
        <span class="graytext" style="font-size: 11px">
        05/13/09  2:02am
        <br>
       </span>
      </td>
     </tr>
    </tbody>
 """

在HTML字符串中,我需要取出日期字符串。

我试过这种方式

  import lxml
  doc = lxml.html.fromstring(s)
  doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]')

但这不起作用。我应该只接受Datestring。

2 个答案:

答案 0 :(得分:1)

您的查询正在选择span,您需要从中获取文字:

>>> doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]')
[<Element span at 1c9d4c8>]

大多数查询返回一个序列,我通常使用一个辅助函数来获取第一个项目。

from lxml import etree
s = """
<tbody>
 <tr>
   <td style="border-bottom: none">
   <span class="graytext" style="font-weight: bold;"> Reply #3 - </span>
    <span class="graytext" style="font-size: 11px">
    05/13/09  2:02am
    <br>
   </span>
  </td>
 </tr>
</tbody>
"""
doc = etree.HTML(s)

def first(sequence,default=None):
  for item in sequence:
    return item
  return default

然后:

>>> doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]')
[<Element span at 1c9d4c8>]
>>> doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]/text()')
['\n    05/13/09  2:02am\n    ']
>>> first(doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]/text()'),'').strip()
'05/13/09  2:02am'

答案 1 :(得分:0)

尝试以下操作而不是最后一行:

print doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]/text()')[0]

xpath表达式的第一部分是正确的,//span[@class="graytext" and @style="font-size: 11px"]选择所有匹配的span节点,然后您需要指定要从节点中选择的内容。此处使用text()选择节点的内容。