如何从Xpath查询中排除元素?

时间:2018-01-07 13:19:07

标签: xpath

我正在尝试选择成分列表中的成分,但也有分散在其中的工具提示(在BBC Good Food网站上)。

作为一个精简的例子:

<li class="ingredients-list__item" itemprop="ingredients">
  400g
  <a href="/glossary/new-potatoes" class="ingredients-list__glossary-link tooltip-processed">
    new potato
    <div id="gf-tooltip-0" class="gf-tooltip" role="tooltip">
      <div class="gf-tooltip__content">
        <div class="gf-tooltip__text">
          <p>unwanted tooltip</p>
        </div>
      </div>
    </div>
  </a>, halved if large
  <span class="ingredients-list__glossary-element" id="ingredients-glossary"></span>
</li>

我试图以'400g new potato, halved if large'或同样好的['400g', 'new potato', ', halved if large']结束。

我尝试过的其他事情:

s.xpath("//li[@class='ingredients-list__item'][not(div[@class='gf-tooltip'])]//text()").extract()

但是这仍然会返回工具提示div中的文本。

1 个答案:

答案 0 :(得分:3)

一种可能的方法是排除文本节点,其中任何祖先都是工具提示div(为了便于阅读,分为2行):

//li[@class='ingredients-list__item']
  //text()[not(ancestor::div[@class='gf-tooltip'])]