1)我正在做一个教程来展示 findElements By xpath 是如何工作的。我想知道为什么它会返回<div>
带有属性的元素后面的所有文本id=container
。
xpath的代码:By.xpath("//div[@id='container']
2)我应该如何修改代码,使其只返回父注释之后的第一个或前几个节点,例如第一个节点如“Home”,前几个节点如 Home、手动测试和自动化测试。
感谢您的建议和帮助!
这是本教程的代码片段:
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
}