XPath简单的条件语句?如果节点X存在,Y是否存在? [英] XPath simple conditional statement? If node X exists, do Y?

查看:41
本文介绍了XPath简单的条件语句?如果节点X存在,Y是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用google文档进行网络抓取.更具体地说,我使用的是内置于IMPORTXML函数中的Google表格,其中使用了XPath选择要从中抓取数据的节点.

I am using google docs for web scraping. More specifically, I am using the Google Sheets built in IMPORTXML function in which I use XPath to select nodes to scrape data from.

我要做的基本上是检查特定节点是否存在,如果是,请选择其他随机节点.

What I am trying to do is basically check if a particular node exists, if YES, select some other random node.

/*IF THIS NODE EXISTS*/
if(exists(//table/tr/td[2]/a/img[@class='special'])){

   /*SELECT THIS NODE*/ 
   //table/tr/td[2]/a

}

推荐答案

您在XPath中没有完全类似的逻辑,但是您可以执行所需的操作.

You don't have logic quite like that in XPath, but you might be able to do something like what you want.

如果您要选择//table/tr/td [2]/a ,但前提是该文件中包含 img [@ class ='special'] ,则可以使用//table/tr/td [2]/a [img [@ class ='special']] .

If you want to select //table/tr/td[2]/a but only if it has a img[@class='special'] in it, then you can use //table/tr/td[2]/a[img[@class='special']].

如果要在其他情况下选择其他节点,则可以合并两个路径( | 运算符),并只需确保每个路径都有一个过滤器即可(在 []之内))是互斥的,就像有一个是路径,另一个是该路径的 not()一样.我举一个例子,但是我不确定您想要什么其他随机节点"……也许您可以澄清一下?

If you want to select some other node in some other circumstance, you could union two paths (the | operator), and just make sure that each has a filter (within []) that is mutually exclusive, like having one be a path and the other be not() of that path. I'd give an example, but I'm not sure what "other random node" you'd want… Perhaps you could clarify?

关键是将XPath视为一种查询语言,而不是一种过程语言,因此您需要考虑选择器和它们上的过滤器,这是与大多数程序员习惯于思考问题的方式完全不同的方式..但是事实是,过滤器不需要专门与选择器相关(例如,您可以有一个过滤器可以开始查看文档的根目录),这带来了一些强大的(如果很难理解的话)可能性.

The key thing is to think of XPath as a querying language, not a procedural one, so you need to be thinking of selectors and filters on them, which is a rather different way of thinking about problems than most programmers are used to. But the fact that the filters don't need to specifically be related to the selector (you can have a filter that starts looking at the root of the document, for instance) leads to some powerful (if hard-to-read) possibilities.

这篇关于XPath简单的条件语句?如果节点X存在,Y是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆