【问题标题】:XPath discriminative text extractionXPath 判别文本提取
【发布时间】:2020-01-13 10:56:26
【问题描述】:

假设我有一个指向以下 HTML 的 XPath 选择器:

<div>
    <p>Hello <a href="foo">fantastic</a> world</p>
    <table>
        <tr>
            <td>first</td>
            <td>row</td>
        </tr>
        <tr>
            <td>second</td>
            <td>row</td>
        </tr>
    </table>
</div>

我想以一种只忽略&lt;a&gt; 标签的方式从中提取文本,这样我会得到:

['Hello fantastic world', 'first', 'row', 'second', 'row']. 

请注意,fantastic 被视为属于 &lt;p&gt; 标记。

问题是:

  • selector.xpath('.//text()').extract(),我明白了

    ['Hello', 'fantastic', 'world', 'first', 'row', 'second', 'row']

  • 'selector.xpath(string(./)).extract()',我明白了

    ['Hello fantastic world first row second row']

如果有人知道如何破解它,将不胜感激!

【问题讨论】:

  • 感谢 kjhughes 的编辑。 @whoever downvoted,你能详细说明为什么吗?

标签: html xml xpath


【解决方案1】:

这个 XPath,

//*[not(self::a)][not(*) or a]

将选择除a 没有子元素或只有a 子元素之外的所有元素:

<p>Hello <a href="foo">fantastic</a> world</p>
<td>first</td>
<td>row</td>
<td>second</td>
<td>row</td>

XPath 2.0 中,直接在 XPath 中获取这些元素的字符串值:

//*[not(self::a)][not(*) or a]/string()

结果,按要求:

Hello fantastic world
first
row
second
row

XPath 1.0 中,迭代结果并提取宿主语言中的字符串值。

【讨论】:

    【解决方案2】:

    还有另一个 xpath 2.0 替代方案:

    //(p,//td)/string()
    

    同样的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-16
      • 2013-03-16
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      相关资源
      最近更新 更多