【问题标题】:Issue with href xpath expressionhref xpath 表达式的问题
【发布时间】:2014-11-01 08:55:39
【问题描述】:

我想从网站解析一些数据。所以,我需要的是用 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 表达式对于所有这三个值应该是不同的。那可能吗? 因此,例如对于 Водка,我们应该包括 href + span class + strong 和 br 之间的值来确定它。 对于соклимона 跨度类+strong和br之间的值等等

【问题讨论】:

    标签: python xpath


    【解决方案1】:

    我不确定您是否想将所有值作为唯一值,例如Водка 作为一个值,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 мл
    

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      相关资源
      最近更新 更多