C# 如何使用XPathforHTML获取子节点数?
我在html中具有以下结构:C# 如何使用XPathforHTML获取子节点数?,c#,html,xpath,selenium-webdriver,C#,Html,Xpath,Selenium Webdriver,我在html中具有以下结构: 1. 2. 3. 如何使用C#和webdriver选择子节点A的计数?这很有效 Program.cs: using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using System; namespace SeleniumTest { class Program { static void Main(string[] args) {
1.
2.
3.
如何使用C#和webdriver选择子节点A的计数?这很有效
Program.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>
第三个粗体元素是否故意损坏?欢迎使用堆栈溢出!我已经删除了该代码段,因为没有要运行的内容。我们还同意删除“提前感谢”或“致以最良好的问候”语句,因为它们对描述问题没有帮助。OP要求“A的子节点”。我认为更正确的说法是:
driver.FindElements(By.XPath”//A/*”
?您的注释版本,By.XPath(“./*”)
,不仅可以找到子元素,还可以找到它们的子元素(如果有的话)。。。有时候,一封信就能带来巨大的不同。不确定这是否适用于HTML。@SiKing感谢您的输入。我更新了答案以反映你的建议。
Child elements1: 3
Child elements2: 5
Child elements3: 4