Java Webdriver findElements 通过 xpath

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16361535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:29:59  来源:igfitidea点击:

Webdriver findElements By xpath

javaseleniumxpathselenium-webdriverwebdriver

提问by user2061466

1)I am doing a tutorial to show how findElements By xpath works. I would like to know why it returns all the texts that following the <div>element with attribute id=container.

1)我正在做一个教程来展示 findElements By xpath 是如何工作的。我想知道为什么它返回<div>带有属性的元素之后的所有文本id=container

code for xpath: By.xpath("//div[@id='container']

xpath 的代码: By.xpath("//div[@id='container']

2) how should I modify the code so it just return first or first few nodes that follow the parent note e.g. first node like 'Home', first few node like, Home, Manual Testing and Automation Testing.

2)我应该如何修改代码,以便它只返回跟随父注释的第一个或前几个节点,例如第一个节点像“主页”,前几个节点像主页,手动测试和自动化测试。

Thanks for your advise and help!

感谢您的建议和帮助!

Here is the code fragment for this tutorial:

这是本教程的代码片段:

import java.util.List;

import org.junit.Test;
import org.junit.Before;
import org.junit.After;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WD_findElements 
{
    @Test
    public void test_byxpath(){

        WebDriver driver = new FirefoxDriver();

        try{
            driver.get("http://www.hexbytes.com");

        List<WebElement> elements = driver.findElements(By.xpath("//div[@id='container']"));    
            System.out.println("Test7 number of elements: " + elements.size());

            for(WebElement ele : elements){
                //ele.sendKeys("hexbyes");
                System.out.println(ele.getText());
                //System.out.println(ele.getAttribute("id"));
                //System.out.println(ele.getTagName());
            } 
        }
        finally {
            driver.close();
        }

    }//end of test_byxpath

 public void xpathDemo2() {
           WebDriver driver = new FirefoxDriver();
           try{
               driver.get("http://www.hexbytes.com");
               WebElement webelement = driver.findElement(By.id("container"));
               //matching single element with attribute value=container
               System.out.println("The id value is: " + webelement.getAttribute("id"));
               System.out.println("The tag name is: " + webelement.getTagName());
           }
           finally {
               driver.close();
           }
       }//end of xpathDemo2 

public void xpathDemo3() {
       WebDriver driver = new FirefoxDriver();
       try{
           driver.get("http://www.hexbytes.com");
          //find first child node of div element with attribute=container
          List<WebElement> elements = driver.findElements(By.xpath("//div[@id='container']/*[1]"));
          System.out.println("Test1 number of elements: " + elements.size()); 

          for(WebElement ele : elements){
              System.out.println(ele.getTagName());
              System.out.println(ele.getAttribute("id"));
              System.out.println("");
              System.out.println("");
          }
   }
   finally {
       driver.close();
   }
 }//end of xpathDemo3
 }

采纳答案by hr_117

Your questions:

你的问题:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText()Where getText will return all text content of all children of your result.

Q 1.) 我想知道为什么它会返回 div 之后的所有文本?
它不应该,我认为不会。它返回所有 'id' 属性值等于 'containter' 的 div(以及它的所有子元素)。但是您正在使用ele.getText()Where getText打印结果将返回结果的所有子项的所有文本内容。

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

获取此元素的可见(即不被 CSS 隐藏)innerText,包括子元素,没有任何前导或尾随空格。
返回:
此元素的innerText。

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

Q 2.) 我应该如何修改代码,使其只返回跟随父注释的第一个或前几个节点
这不是很清楚你在找什么。例子:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

以下到 div 的父级是 p2。这将是:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

或更短

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1]- for the first one. or [position() &lt; 4]for the first three)

如果您只查找带有“谓词”的表达式的第一个范围(例如[1]- 对于第一个。或[position() &lt; 4]对于前三个)

If your are looking for the first child of the first div:

如果您正在寻找第一个 div 的第一个孩子:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

如果只有一个带有 id 的 div,您正在寻找第一个孩子:

   //div[@id='container']/*[1]

and so on.

等等。

回答by Arran

The XPath turns into this:

XPath 变成这样:

Get me all of the divelements that have an id equalto container.

给我所有的DIV有一个id元素等于容器

As for getting the first etc, you have two options.

至于获得第一个等,你有两个选择。

Turn it into a .findElement()- this will just return the first one for you anyway.

把它变成一个.findElement()- 无论如何,这只会为你返回第一个。

or

或者

To explicitly do this in XPath, you'd be looking at:

要在 XPath 中明确执行此操作,您需要查看:

(//div[@id='container'])[1]

for the first one, for the second etc:

对于第一个,对于第二个等等:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the lastelement found:

然后 XPath 有一个特殊的索引器,称为last,它会(你猜对了)让你找到最后一个元素:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1not 0like they do in most programming languages.

值得一提的是,XPath 索引器将从1开始,而不是像大多数编程语言那样从0开始。

As for getting the parent 'node', well, you can use parent:

至于获取父“节点”,好吧,您可以使用parent

//div[@id='container']/parent::*

That would get the div's direct parent.

这将获得div的直接父级。

You could then go further and say I want the first*div* with an id of container, and I want hisparent:

然后你可以更进一步说我想要第一个* div* id 为container,我想要他的父母:

(//div[@id='container'])[1]/parent::*

Hope that helps!

希望有帮助!

回答by user3487861

Instead of

代替

css=#container

use

css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)