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
.
code for 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.
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
}