href xpath表达式问题

时间:2014-11-01 08:55:40

标签: python xpath

我想从网站解析一些数据。所以,我需要的是用xpath捕获一些值。 我有这个HTML代码来解析。

<fieldset class="fieldgroup group-ingred">
<legend>Основные ингредиенты:</legend>
<strong><a href="/glossary/vodka"><span class="ingredient">Водка</span></a>- </strong>30 мл,<br />
<strong><span class="ingredient">Сок лимона</span> - </strong>30 мл,<br />
<strong>А также: </strong><span class="ingredient">Лёд</span>.<br />
<strong>При приготовлении понадобятся: </strong>Соломинка.</fieldset>

我有这个Соломинка:

//fieldset[@class='fieldgroup group-ingred']/child::text()[last()] 

但我还需要解析

Водка 30 мл
Сок лимона 30 мл
Лед

作为唯一值,因此对于所有这三个值,xpath exparession应该是不同的。那可能吗? 因此,例如对于Водка,我们应该在strong和br 之间包含 href + span class +值来确定它。 对于соклимона span class + strong和br之间的值等等

1 个答案:

答案 0 :(得分:0)

我不确定您是否要将所有值都设为唯一值,例如Водка作为一个值,30мл作为第二个值,或Водка30мл作为一个完整的xpath结果,所以我将提供:

(//fieldset[@class='fieldgroup group-ingred']//span[@class='ingredient'])
 [1]/text()   // Result: Водка
(//fieldset[@class='fieldgroup group-ingred']//span[@class='ingredient'])
 [2]/text()   // Result: Сок лимона
(//fieldset[@class='fieldgroup group-ingred']//span[@class='ingredient'])
 [3]/text()   // Result: Лёд

(//fieldset[@class='fieldgroup group-ingred']//span[@class='ingredient']/
 parent::a/parent::strong/following-sibling::text())[1]
// Result: 30 мл, - to get 30 мл without the ",", use substring-before:
substring-before((//fieldset[@class='fieldgroup group-ingred']//
span[@class='ingredient']/parent::a/parent::strong/following-sibling::text())[1],',')


(//fieldset[@class='fieldgroup group-ingred']//span[@class='ingredient']/
 parent::strong/following-sibling::text())[1]  // Result: the 30 мл, for Сок лимона

获得综合结果 - 例如Водка 30 мл - 您可以使用concat()

concat(
 (//fieldset[@class='fieldgroup group-ingred']//
    span[@class='ingredient'])[1]/text(),
    ' ',
    substring-before(
      (//fieldset[@class='fieldgroup group-ingred']//
       span[@class='ingredient']/parent::a/parent::strong/
       following-sibling::text())[1],',')
)    // Result: Водка 30 мл

concat(
 (//fieldset[@class='fieldgroup group-ingred']//
    span[@class='ingredient'])[2]/text(),
    ' ',
    substring-before(
      (//fieldset[@class='fieldgroup group-ingred']//
         span[@class='ingredient']/parent::strong/
         following-sibling::text())[1],',')
)   // Result: Сок лимона 30 мл