如何编写xpath来获取Child节点及其属性?

时间:2018-01-10 18:27:03

标签: selenium selenium-webdriver

我有一个场景,我已经在列表中存储了所有父节点“// td”,现在我需要获取列表中每个元素的子节点的详细信息。这是我的代码:

WebDriver driver = new ChromeDriver();
    driver.get("https://jqueryui.com/datepicker/");

    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);

    driver.switchTo().frame(0);

    driver.findElement(By.xpath("//*[@id='datepicker']")).click();

    WebElement Calendertable = driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']//tbody"));

    List<WebElement> Date = Calendertable.findElements(By.tagName("td"));

    System.out.println(Date.size());

    for( WebElement e : Date) {

            System.out.println(e.findElement(By.xpath(".//a")).getAttribute("class"));

        }

xpath details of element

我需要获取“td”节点的所有子节点的详细信息。我写了代码,但它没有用。它为“.//a”元素抛出“NoSuchElementException:”。

请建议

3 个答案:

答案 0 :(得分:2)

我认为原因是因为某些<td>单元格(即表格的开头和结尾,没有日期,没有a子标签,例如:

<td class=" ui-datepicker-week-end ui-datepicker-other-month ui-datepicker-unselectable ui-state-disabled">&nbsp;</td>

因此,您可以通过检查td没有unselectabledisabled类来解决此问题:

if(!e.getAttribute("class").contains("disabled")) {
  System.out.println(
      e.findElement(By.xpath(".//a")).getAttribute("class"));
    }

但更好的是:您可以只搜索一下您关心的元素(atd),而不是多次搜索:

List<WebElement> aInDate = driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']//tbody//td/a"));

for( WebElement a : aInDate) { 
    System.out.println(a.getAttribute("class")); }

答案 1 :(得分:1)

尝试使用您感兴趣的确切子节点创建列表,然后尝试从元素中提取text,而不是尝试获取列表中每个元素的子节点的详细信息:

List<WebElement> Date = Calendertable.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//tbody//tr//td/a[@class='ui-state-default']"));
System.out.println(Date.size());
for( WebElement e : Date) 
{
    System.out.println(e.getAttribute("innerHTML"));
}

答案 2 :(得分:0)

有一种更简单的方法可以做到这一点。您不必循环遍历所有单元格并查找所需单元格,然后单击它。您可以使用XPath创建一个定位器,它将为您提供您想要的第一天。当我编写功能代码时,我可能会反复使用(比如选择一天),我通常会编写一个函数,以便它可以很容易地重用。

代码

driver.get("https://jqueryui.com/datepicker/");
driver.switchTo().frame(0);
driver.findElement(By.id("datepicker")).click();
chooseDay(11);

功能

public static void chooseDay(int day)
{
    driver.findElement(By.xpath("//div[@id='ui-datepicker-div']//a[.='" + day + "']")).click();
}

基本上你调用chooseDay()函数并在你想要点击的那一天传递。该函数会查找包含您选择日期并点击它的A代码。

这是有效的代码。