从 HTML 文件中间的设定点提取上下文

发布于 2024-08-20 06:38:36 字数 812 浏览 2 评论 0原文

我有一些 HTML,并且正在某个点提取一个片段(内嵌图像),但我想显示该图像周围的一些上下文。

我正在使用 PHP,并且我知道 Symfony 和 Wordpress 都提供了处理在某些 HTML 中间切碎文本时发生的情况的函数(它会关闭所有打开的标签),但没有提供处理另一个方向的片段的函数。

因此,在这种情况下:

 'Snippet of text and a <a href="#moo">link right her'

我可以使用上述函数来修复,但是呢:

'nk right here</a> and then more text after the link.'

我已经考虑过即使是标签结束片段也可能是错误的解决方法的可能性,而我应该使用 Xpath 解析 HTML。但是,我找不到任何使用 xpath 创建这样的片段的示例或提及。

更新:

所以我当前的想法是:

  1. 向上移动解析树,直到到达包含所有内容的标签(在我的情况下为 div class=post )。该 div 之前的最后一个节点是起点(最有可能是 ap 标签)。

  2. 从这里获取前一个同级(应该再次是 ap 标签)。

  3. 下降到该节点并获取最后一个子节点,将文本内容保存到临时字符串中。继续向后浏览这些子节点,直到我们获得足够的片段。

这仍然不理想,因为我不确定我需要走多远才能获取文本内容。

有谁知道这个想法在任何地方的实施吗?

I have some HTML, and I'm extracting a snippet at a certain point (an inline image), but I'd like to show some context around this image.

I'm using PHP, and I know that both Symfony and Wordpress provide functions for dealing with what happens when you chop up text in the middle of some HTML (it closes all open tags), but nothing for dealing with snippets in the other direction.

So, in the case of :

 'Snippet of text and a <a href="#moo">link right her'

I can use the above-mentioned function to fix, but what about:

'nk right here</a> and then more text after the link.'

I've considered the possibility that even the tag-closing snippet is probably the wrong way to go about this, and I should instead be using Xpath to parse the HTML. However, I can't find any examples or mentions of using xpath to create snippets like this.

Update:

So my current idea is:

  1. move up the parse tree until I get to the tag that encloses all the content (div class=post in my case). The last node that I have before this div is the starting point (most likely a p tag).

  2. From here, get the previous sibling (which should be a p tag again).

  3. Descend into this node and get the last children, saving the text content to a temporary string. Keep stepping back through these children, until we get enough of a snippet.

This still ins't ideal, as I'm not sure how far I'll have to step down to get the text content.

Does anyone know of an implementation of this idea anywhere?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留蓝 2024-08-27 06:38:36

这不是一个完整的答案,但您可以使用 xpath 查询来获取您感兴趣的节点,然后使用 nextSibling 和 previousSibling 属性(以扩展支持的任何形式)来获取该节点的上下文节点。

This isn't a complete answer, but you can use an xpath query to get just the node(s) you're interested in, then us the nextSibling and previousSibling properties (in whatever form supported by the extension) to get context for the node(s).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文