为什么我在指定索引时使用XPath查找到两个元素?

huangapple go评论70阅读模式
英文:

Why I find two elements using xpath when I specify index?

问题

我正在编写自动化测试。
用于查找元素,我正在使用XPATH。
现在,我需要获取元素列表,通常我会编写包含表格类名称和子元素的XPATH。我的页面上有2个表格,我的XPATH可以同时找到这两个表格,但是当我使用索引1时,也会找到第二个表格,当我使用索引2时,却什么都找不到。

这是如何工作的?为什么我不能选择第二个元素?

英文:

I'm writing autotests.
For finding elements I'm using XPATH.
Now I need get list of element, as usual I write xpath which contains class name of table and childs elements. My page has 2 tables, and my XPATH can find both, but when I'm using index 1 I also find second table, when I'm using index 2 I find nothing.

How does it work? Why I can't choose second element

为什么我在指定索引时使用XPath查找到两个元素?

答案1

得分: 0

根据我所看到的XPath片段,您正在选择第一个后续兄弟table元素的子元素tbody。大多数table只会有一个tbody元素。因此,在第一个XPath中添加[1]来获取第一个tbody时,您会得到它。在第二个XPath中添加[2]来获取该table的第二个tbody时,没有要选择的内容,因此什么都不会得到。

英文:

From the pieces of the XPath that I can see, at the step in which you are selecting the tbody element that is the child of the first following-sibling table element.

Most table will only have one tbody element.

So, in the first XPath where you add [1] asking for the first tbody, you get it. In the second XPath where you are asking for [2], the second tbody that is the child of that table, there aren't any to select and you get nothing.

答案2

得分: 0

我相当确定问题出在你的XPath中红色部分。

所以在你的XPath中红色部分会有2个带有表格的元素。

要只选择第一个元素,你可以像这样将()放在它们周围:

(//div[@class='with-some-classname']/following-sibling::table)1/tbody

另一个选项是在XPath的红色部分中将表格作为谓词使用,就像这样:

(//div[@class='with-some-classname'][following-sibling::table])1/following-sibling::table1/tbody

英文:

I'm pretty sure that the reason liesin the red part of your XPath.

So in the red part of your XPath will have 2 elements with a table.

To only select the first one you can put () around them like this:

(//div[@class='with-some-classname']/following-sibling::table)[1]/tbody

An other option would be to use the table as a predicate in your red part of the XPath like this i.e.:

(//div[@class='with-some-classname'][following-sibling::table])[1]/following-sibling::table[1]/tbody

huangapple
  • 本文由 发表于 2023年7月11日 02:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定