xpath 的双斜杠.硒 Java 网络驱动程序 [英] double slash for xpath. Selenium Java Webdriver

查看:27
本文介绍了xpath 的双斜杠.硒 Java 网络驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Selenium WebDriver.我对 xpath 有疑问.

如果我有以下代码示例:

<div><div><a><div>

</a>

我想找到最后一个

中的元素.我想我有 2 个使用 xpath 的选项.

第一个选项是单斜杠:

driver.findElement(By.xpath("/div/div/div/a/div")).click();

第二个选项是使用双斜线(这是我有疑问的地方).

driver.findElement(By.xpath("//a/div")).click();

是否会直接在 中搜索,但是如果 html 示例代码只是更大代码的一部分,而在这个更大的代码中更多的是"?这种方法具体在哪里看?

例如,如果我这样做会发生什么:

driver.findElement(By.xpath("//div")).click();

如果每个

如您所见,我添加了另外两个 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屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆