英文:
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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论