xpath 的双斜杠.硒 Java 网络驱动程序 [英] double slash for xpath. Selenium Java Webdriver
问题描述
我正在使用 Selenium WebDriver.我对 xpath 有疑问.
如果我有以下代码示例:
<div><div><a><div></a>
我想找到最后一个
第一个选项是单斜杠:
driver.findElement(By.xpath("/div/div/div/a/div")).click();
第二个选项是使用双斜线(这是我有疑问的地方).
driver.findElement(By.xpath("//a/div")).click();
是否会直接在 中搜索,但是如果 html 示例代码只是更大代码的一部分,而在这个更大的代码中更多的是
"?这种方法具体在哪里看?
例如,如果我这样做会发生什么:
driver.findElement(By.xpath("//div")).click();
如果每个
首先,避免 //
通常是正确的做法 - 因此,您展示的第一个表达式是完美的.
如果每个
是的,没错.一个 XPath 表达式,如
//div
将选择文档中的所有 div
元素,无论它们在哪里.
如果 html 示例代码只是更大代码的一部分,而在这个更大的代码中包含更多 <a>
,会发生什么?这种方法具体在哪里看?
然后,让我们让 HTML更大":
<a><p>C</p></a><div><div><a><div>A</div></a><a><div>B</div></a>
如您所见,我添加了另外两个 a
元素 - 其中只有一个包含 div
元素.假设这个新文档作为输入,那么
/div/div/div/a/div
这将选择 only
作为结果,和
//a/div
这将同时选择
和
- 因为 a 的确切位置
在树中现在无关紧要.但是它们都不会选择包含 p
的第一个 a
元素.
I am using Selenium WebDriver. I have a doubt about the xpath.
If I have the following code example:
<div>
<div>
<div>
<a>
<div>
</div>
</a>
</div>
</div>
</div>
And I want to locate the element which is in the last <div>
. I think I have 2 options with the xpath.
First option is with single slash:
driver.findElement(By.xpath("/div/div/div/a/div")).click();
Second option is using double slash (and here is where I have the doubt).
driver.findElement(By.xpath("//a/div")).click();
Is it going to search in the <a>
directly, but what happens if the html example code was just a part of a bigger code and in this bigger code are more "<a>
"?. Where would this method look exactly?
What happens for example if I do it like this:
driver.findElement(By.xpath("//div")).click();
Would it looks if every <div>
found in the html code?
First of all, avoiding //
is usually the right thing to do - so, the first expression you show is perfect.
Would it looks if every
<div>
found in the html code?
Yes, exactly. An XPath expression like
//div
will select all div
elements in the document, regardless of where they are.
what happens if the html example code was just a part of a bigger code and in this bigger code are more
<a>
?. Where would this method look exactly?
Then, let us make the HTML "bigger":
<div>
<a>
<p>C</p>
</a>
<div>
<div>
<a>
<div>A</div>
</a>
</div>
<a>
<div>B</div>
</a>
</div>
</div>
As you can see, I have added two more a
elements - only one of them contains a div
element. Assuming this new document as the input, there will now be a difference between
/div/div/div/a/div
which will select only <div>A</div>
as the result, and
//a/div
which will select both <div>A</div>
and <div>B</div>
- because the exact position of a
in the tree is now irrelevant. But none of them will select the first a
element that contains p
.
这篇关于xpath 的双斜杠.硒 Java 网络驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!