如何使用xpath和正则表达式在Python中更优雅地提取数字

时间:2014-04-09 15:59:43

标签: python regex xpath scrapy

我有一个小的html片段,我想从中提取 - 实际上是一个等级。我正在使用Python scrapyre

我的代码有效,但远非好看。

以下是html片段,我只想从中获取2

<div id="left">
<div class="0"><b>Certificate:</b></div>
<div class="1">
<div></div>
<div>
<a class="link" href="new.html">Maths</a>&nbsp;(First)&nbsp;&nbsp;&nbsp;Grade 2<br>
</div>
</div>
<div class="2"></div>
</div>

以下是我到目前为止解决的问题:

! note = sel.xpath('//*[@id="left"]/div[2]/div[2]/text()[2]').extract()
! print note
> [u'\xa0(First)\xa0\xa0\xa0Grade 2']
! note_string = ''.join(note)
! note_only = re.search(r'\d+', note_string).group()
> 2

将列表转换为字符串以提取如此微小的信息肯定不是最佳做法。

我怎样才能做得更好?

1 个答案:

答案 0 :(得分:3)

您可以使用以下XPath表达式来获取2

substring-after(//*[@id="left"]/div[2]/div[2]/text(), "Grade ")