如何使用 XPath 在另一个子元素之后选择子文本

Kub*_*hon 5 html xml xpath

我正在使用 Crawler 库,它可以帮助您创建一些 XPath 表达式来获取 HTML 标记的内容。我目前正在从页面读取 HTML5 内容,并且我想以这种方式检索未插入标签的文本。

<div class="country">
    <strong> USA </strong>
        Some text here
</div>
Run Code Online (Sandbox Code Playgroud)

所以我正在尝试获取此文本Some text here但爬虫库允许获取标签中的内容而不是标签之外的内容。

所以请提供任何替代方案。

这些是爬虫部分:

$crawler = new Crawler();
$crawler->xpathSingle($xml, '//div[@class="country"]/strong/@text');
Run Code Online (Sandbox Code Playgroud)

kjh*_*hes 3

"Some text here"这些 XPath 中的任何一个都将按请求返回:

  • normalize-space(substring-after(//div[@class="country"], 'USA'))

  • normalize-space(//div[@class="country"]/strong/following-sibling::text())

根据您希望适应的变化类型进行选择。

信用:第二个例子源自@Keith Hall 在评论中首先提出建议


更新

正如我提到的,您需要根据您希望适应的变体来选择 XPath。我刚发帖,你就遇到了一个变化:

<div class="country">
    <strong> USA </strong>
        Some text here
    <i>Do not want this text</i>
</div>
Run Code Online (Sandbox Code Playgroud)

您可以使用上面的第二个 XPath 根据请求排除"Do not want this text"并返回"Some text here",但只需获取以下第一个文本节点:

  • normalize-space(//div[@class="country"]/strong/following-sibling::text()[1])