gpt4 book ai didi

c# - 如何使用 XPath for HTML 获取子节点的数量?

转载 作者:行者123 更新时间:2023-12-02 11:01:36 25 4
gpt4 key购买 nike

我在 html 中有以下结构:

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

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

最佳答案

这有效...

程序.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();
}
}
}
}

测试.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

关于c# - 如何使用 XPath for HTML 获取子节点的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com