【问题标题】:How to get the number of child nodes using XPath for HTML?如何使用 XPath for HTML 获取子节点的数量?
【发布时间】:2015-07-04 23:12:36
【问题描述】:

我在 html 中有以下结构:

<A>
   <b>1</b>
   <b>2</b>
   <b>3</b>
</A>

如何使用 C# 和 webdriver 选择子节点 A 的数量?

【问题讨论】:

  • 第三个粗体元素是否被故意破坏了?
  • 欢迎来到 Stack Overflow!我已经删除了 sn-p,因为没有什么可以运行的。我们还同意删除“提前致谢”或“最好的问候”声明,因为它们无助于描述问题。

标签: c# html xpath selenium-webdriver


【解决方案1】:

这行得通...

程序.cs:

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;


namespace SeleniumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FirefoxDriver driver = new FirefoxDriver())
            {
                driver.Navigate().GoToUrl("file://" + AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "test.html");
                //Use this line to capture all child "b" elements
                var bElements = driver.FindElementByXPath("//A").FindElements(By.TagName("b"));
                //Use the line below to capture all descendants
                var bElements2 = driver.FindElementByXPath("//A").FindElements(By.XPath(".//*"));
                //Use the line below to capture all immediate child elements
                var bElements3 = driver.FindElementsByXPath("//A/*");

                Console.WriteLine("Child elements1: " + bElements.Count);
                Console.WriteLine("Child elements2: " + bElements2.Count);
                Console.WriteLine("Child elements3: " + bElements3.Count);

                driver.Close();
            }
        }
    }
}

Test.html:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>test</title>
</head>
<body>
    <A>
        <b>1</b>
        <b>2</b>
        <b>3
            <c>4</c>
        </b>
        <z>5</z>
    </A>

</body>
</html>

输出:

Child elements1: 3
Child elements2: 5
Child elements3: 4

【讨论】:

  • OP 要求“A 的子节点”。我认为更正确的说法是:driver.FindElements(By.XPath"//A/*")?您的评论版本 By.XPath(".//*") 不仅会找到子元素,还会找到他们的子元素(如果有的话)。
  • HTML, XHTML, ... 有时一个字母就能产生巨大的影响。不确定这是否适用于 HTML。
  • @SiKing 感谢您的意见。我已更新答案以反映您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2012-03-01
  • 2011-01-25
  • 2015-03-30
  • 2012-09-17
  • 1970-01-01
相关资源
最近更新 更多