CsQuery操作详解
目录
"CsQuery 是一个功能强大且易于使用的 C# 库,模仿了 jQuery 的 API,使得在 C# 中解析和操作 HTML 文档变得更加直观。以下是一个详细的示例,涵盖了 CsQuery 的各种操作,包括加载 HTML、选择元素、提取和修改属性、操作文本内容、处理样式等。"
1. 安装 CsQuery
首先,确保你的项目中安装了 CsQuery。你可以通过 NuGet 包管理器来安装:
Install-Package CsQuery
或者在 .csproj 文件中添加
<PackageReference Include="CsQuery" Version="1.3.0" />
2. 示例 HTML
假设我们有以下 HTML 内容,需要解析和操作:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="highlight">Welcome to CsQuery</h1>
<p>This is a <span class="highlight">simple</span> example.</p>
<a href="https://example.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe" />
<input type="password" id="password" />
</body>
</html>
3. 使用 CsQuery 进行 HTML 解析与操作
以下是一个详细的 C# 示例,展示如何使用 CsQuery 进行各种操作:
using CsQuery;
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// 示例 HTML 内容
string html = @"
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id='main-heading' class='highlight'>Welcome to CsQuery</h1>
<p>This is a <span class='highlight'>simple</span> example.</p>
<a href='https://example.com' target='_blank'>Visit Example.com</a>
<ul id='items'>
<li class='item'>Item 1</li>
<li class='item'>Item 2</li>
<li class='item'>Item 3</li>
</ul>
<input type='text' id='username' value='JohnDoe' />
<input type='password' id='password' />
</body>
</html>";
// 加载 HTML 文档
CQ dom = CQ.Create(html);
// 1. **选择元素**
// 使用 CSS 选择器选择所有具有 class 'highlight' 的元素
var highlights = dom.Select(".highlight"); //简写: dom[".highlight"];
Console.WriteLine("Elements with class 'highlight':");
foreach (var elem in highlights)
{
Console.WriteLine($"- <{elem.TagName}>: {elem.InnerText}");
}
// 使用 ID 选择器选择特定元素
var mainHeading = dom.Select("#main-heading");
Console.WriteLine($"\nElement with ID 'main-heading': {mainHeading.Text()}");
// 选择所有 <a> 标签
var links = dom.Select("a");
Console.WriteLine("\nAll <a> elements:");
foreach (var link in links)
{
Console.WriteLine($"- Text: {link.InnerText}, Href: {link.GetAttribute("href")}, Target: {link.GetAttribute("target")}");
}
// 选择所有具有 class 'item' 的 <li> 元素
var items = dom.Select("li.item");
Console.WriteLine("\nList items with class 'item':");
foreach (var item in items)
{
Console.WriteLine($"- {item.InnerText}");
}
// 选择特定类型的输入元素
var textInput = dom.Select("input[type='text']");
var passwordInput = dom.Select("input[type='password']");
Console.WriteLine($"\nText Input Value: {textInput.Val()}");
Console.WriteLine($"Password Input Value: {passwordInput.Val()}");
// 2. **提取和修改属性**
// 获取第一个链接的 href 属性,也可用 Attr("href") 来获取属性
string firstLinkHref = links.First().GetAttribute("href"); //或.Attr("href");
Console.WriteLine($"\nFirst link href: {firstLinkHref}");
// 修改第一个链接的 href 属性
links.First().SetAttribute("href", "https://newexample.com"); //或 .Attr("href", "https://newexample.com");
Console.WriteLine($"Modified first link href: {links.First().GetAttribute("href")}");
// 3. **提取和修改文本内容**
// 获取第一个段落的文本内容
var firstParagraph = dom.Select("p").First();
Console.WriteLine($"\nFirst paragraph text: {firstParagraph.Text()}");
// 修改第一个段落的文本内容
firstParagraph.Text("This is an <strong>updated</strong> example.");
Console.WriteLine($"Modified first paragraph HTML: {firstParagraph.Html()}");
// 4. **操作样式**
// 获取元素的 class 属性
string h1Classes = mainHeading.First().GetAttribute("class");
Console.WriteLine($"\nMain heading classes: {h1Classes}");
// 添加一个新的 class
mainHeading.AddClass("new-class");
Console.WriteLine($"Main heading classes after adding 'new-class': {mainHeading.First().GetAttribute("class")}");
// 移除一个 class
mainHeading.RemoveClass("highlight");
Console.WriteLine($"Main heading classes after removing 'highlight': {mainHeading.First().GetAttribute("class")}");
// 5. **遍历和查询 DOM**
// 遍历所有子节点的标签名
Console.WriteLine("\nChild elements of <body>:");
var bodyChildren = dom.Select("body").Children();
foreach (var child in bodyChildren)
{
Console.WriteLine($"- <{child.TagName}>");
}
// 查找包含特定文本的元素
var elementsWithText = dom.Select("*").Where(e => e.InnerText.Contains("simple"));
Console.WriteLine("\nElements containing the text 'simple':");
foreach (var elem in elementsWithText)
{
Console.WriteLine($"- <{elem.TagName}>: {elem.InnerText}");
}
// 6. **生成和输出修改后的 HTML**
string modifiedHtml = dom.Render();
Console.WriteLine("\nModified HTML:");
Console.WriteLine(modifiedHtml);
}
}
4. 代码详解
让我们逐步解释上面的代码,了解 CsQuery 的各种功能:
1. 加载 HTML 文档
CQ dom = CQ.Create(html);
- 使用 CQ.Create 方法加载 HTML 字符串,返回一个 CQ 对象,代表整个 DOM。
2. 选择元素
var highlights = dom.Select(".highlight");
var mainHeading = dom.Select("#main-heading");
var links = dom.Select("a");
var items = dom.Select("li.item");
var textInput = dom.Select("input[type='text']");
var passwordInput = dom.Select("input[type='password']");
//简写的方式
var element = dom[".highlight"];
...
- CSS 选择器:CsQuery 支持大部分标准的 CSS 选择器,如类选择器 (.class)、ID 选择器 (#id)、元素选择器 (tag)、属性选择器 ([attr='value']) 等。
- 多重选择器:例如,li.item 选择所有 <li> 元素且具有 item 类的元素。
3. 提取和修改属性
string firstLinkHref = links.First().GetAttribute("href");
links.First().SetAttribute("href", "https://newexample.com");
//简写的方式
string firstLinkHref = links.First().Attr("href");
links.First().Attr("href", "https://newexample.com");
- 获取属性:使用 GetAttribute("attrName") 或 Attr("attrName")方法获取指定属性的值。
- 设置属性:使用 SetAttribute("attrName", "value") 或 Attr("attrName", "value")方法修改属性的值。
4. 提取和修改文本内容
var firstParagraph = dom.Select("p").First();
firstParagraph.Text("This is an <strong>updated</strong> example.");
- 获取文本:使用 Text() 方法获取元素的文本内容。
- 设置文本:传递新文本给 Text() 方法修改元素的内容。请注意,如果你想插入 HTML 内容,可以使用 Html() 方法。
firstParagraph.Html("This is an <strong>updated</strong> example.");
5. 操作样式
string h1Classes = mainHeading.First().GetAttribute("class");
mainHeading.AddClass("new-class");
mainHeading.RemoveClass("highlight");
- 获取类:通过 GetAttribute("class") 或 Attr("class") 获取元素的类名。
- 添加类:使用 AddClass("className") 方法向元素添加新的类。
- 移除类:使用 RemoveClass("className") 方法从元素移除指定的类。
6. 遍历和查询 DOM
var bodyChildren = dom.Select("body").Children();
foreach (var child in bodyChildren)
{
Console.WriteLine($"- <{child.TagName}>");
}
var elementsWithText = dom.Select("*").Where(e => e.InnerText.Contains("simple"));
- 遍历子节点:使用 Children() 方法获取指定元素的所有直接子节点。
- 条件查询:使用 LINQ 查询来筛选符合特定条件的元素,例如包含特定文本的元素。
7. 生成和输出修改后的 HTML
string modifiedHtml = dom.Render();
Console.WriteLine("\nModified HTML:");
Console.WriteLine(modifiedHtml);
- 渲染 HTML:使用 Render() 方法生成修改后的 HTML 字符串,包含所有更改。
5. 运行示例
运行上述代码,将会输出如下内容:
Elements with class 'highlight':
- <h1>: Welcome to CsQuery
- <span>: simple
Element with ID 'main-heading': Welcome to CsQuery
All <a> elements:
- Text: Visit Example.com, Href: https://example.com, Target: _blank
List items with class 'item':
- Item 1
- Item 2
- Item 3
Text Input Value: JohnDoe
Password Input Value:
First link href: https://example.com
Modified first link href: https://newexample.com
First paragraph text: This is a simple example.
Modified first paragraph HTML: This is an <strong>updated</strong> example.
Main heading classes: highlight
Main heading classes after adding 'new-class': highlight new-class
Main heading classes after removing 'highlight': new-class
Child elements of <body>:
- <h1>
- <p>
- <a>
- <ul>
- <input>
- <input>
Elements containing the text 'simple':
- <span>: simple
Modified HTML:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="new-class">Welcome to CsQuery</h1>
<p>This is an <strong>updated</strong> example.</p>
<a href="https://newexample.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe">
<input type="password" id="password">
</body>
</html>
6. 进一步操作示例
1.添加新元素
// 创建一个新的 <div> 元素
var newDiv = CQ.Create("<div class='new-div'>This is a new div</div>").First();
// 将新元素添加到 <body> 中
dom.Select("body").Append(newDiv);
Console.WriteLine("\nAfter adding a new div:");
Console.WriteLine(dom.Render());
2.删除元素
// 删除第一个列表项
var firstItem = dom.Select("li.item").First();
firstItem.Remove();
Console.WriteLine("\nAfter removing the first list item:");
Console.WriteLine(dom.Render());
3.修改元素属性
// 修改输入框的 placeholder 属性
textInput.SetAttribute("placeholder", "Enter your username");
Console.WriteLine("\nAfter setting placeholder for text input:");
Console.WriteLine(dom.Render());
4.提取元素样式
CsQuery 不直接解析 CSS 样式,但你可以手动提取 <style> 标签中的 CSS 规则:
// 提取所有 <style> 标签的内容
var styles = dom.Select("style");
foreach (var style in styles)
{
Console.WriteLine("\nStyles in <style> tag:");
Console.WriteLine(style.InnerText);
}
7. 完整示例代码
整合以上所有操作,形成一个完整的示例:
using CsQuery;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// 示例 HTML 内容
string html = @"
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id='main-heading' class='highlight'>Welcome to CsQuery</h1>
<p>This is a <span class='highlight'>simple</span> example.</p>
<a href='https://example.com' target='_blank'>Visit Example.com</a>
<ul id='items'>
<li class='item'>Item 1</li>
<li class='item'>Item 2</li>
<li class='item'>Item 3</li>
</ul>
<input type='text' id='username' value='JohnDoe' />
<input type='password' id='password' />
</body>
</html>";
// 加载 HTML 文档
CQ dom = CQ.Create(html);
// 1. **选择元素并提取信息**
var highlights = dom.Select(".highlight");
Console.WriteLine("Elements with class 'highlight':");
foreach (var elem in highlights)
{
Console.WriteLine($"- <{elem.TagName}>: {elem.InnerText}");
}
var mainHeading = dom.Select("#main-heading");
Console.WriteLine($"\nElement with ID 'main-heading': {mainHeading.Text()}");
var links = dom.Select("a");
Console.WriteLine("\nAll <a> elements:");
foreach (var link in links)
{
Console.WriteLine($"- Text: {link.InnerText}, Href: {link.GetAttribute("href")}, Target: {link.GetAttribute("target")}");
}
var items = dom.Select("li.item");
Console.WriteLine("\nList items with class 'item':");
foreach (var item in items)
{
Console.WriteLine($"- {item.InnerText}");
}
var textInput = dom.Select("input[type='text']");
var passwordInput = dom.Select("input[type='password']");
Console.WriteLine($"\nText Input Value: {textInput.Val()}");
Console.WriteLine($"Password Input Value: {passwordInput.Val()}");
// 2. **提取和修改属性**
string firstLinkHref = links.First().GetAttribute("href");
Console.WriteLine($"\nFirst link href: {firstLinkHref}");
links.First().SetAttribute("href", "https://newexample.com");
Console.WriteLine($"Modified first link href: {links.First().GetAttribute("href")}");
// 3. **提取和修改文本内容**
var firstParagraph = dom.Select("p").First();
Console.WriteLine($"\nFirst paragraph text: {firstParagraph.Text()}");
firstParagraph.Html("This is an <strong>updated</strong> example.");
Console.WriteLine($"Modified first paragraph HTML: {firstParagraph.Html()}");
// 4. **操作样式**
string h1Classes = mainHeading.First().GetAttribute("class");
Console.WriteLine($"\nMain heading classes: {h1Classes}");
mainHeading.AddClass("new-class");
Console.WriteLine($"Main heading classes after adding 'new-class': {mainHeading.First().GetAttribute("class")}");
mainHeading.RemoveClass("highlight");
Console.WriteLine($"Main heading classes after removing 'highlight': {mainHeading.First().GetAttribute("class")}");
// 5. **遍历和查询 DOM**
var bodyChildren = dom.Select("body").Children();
Console.WriteLine("\nChild elements of <body>:");
foreach (var child in bodyChildren)
{
Console.WriteLine($"- <{child.TagName}>");
}
var elementsWithText = dom.Select("*").Where(e => e.InnerText.Contains("simple"));
Console.WriteLine("\nElements containing the text 'simple':");
foreach (var elem in elementsWithText)
{
Console.WriteLine($"- <{elem.TagName}>: {elem.InnerText}");
}
// 6. **添加新元素**
var newDiv = CQ.Create("<div class='new-div'>This is a new div</div>").First();
dom.Select("body").Append(newDiv);
Console.WriteLine("\nAfter adding a new div:");
Console.WriteLine(dom.Render());
// 7. **删除元素**
var firstItem = dom.Select("li.item").First();
firstItem.Remove();
Console.WriteLine("\nAfter removing the first list item:");
Console.WriteLine(dom.Render());
// 8. **修改元素属性**
textInput.SetAttribute("placeholder", "Enter your username");
Console.WriteLine("\nAfter setting placeholder for text input:");
Console.WriteLine(dom.Render());
// 9. **提取元素样式**
var styles = dom.Select("style");
foreach (var style in styles)
{
Console.WriteLine("\nStyles in <style> tag:");
Console.WriteLine(style.InnerText);
}
// 10. **生成和输出修改后的 HTML**
string modifiedHtml = dom.Render();
Console.WriteLine("\nModified HTML:");
Console.WriteLine(modifiedHtml);
}
}
8. 运行示例与输出
运行上述代码,将依次执行以下操作,并输出相应的信息:
- 选择具有特定类的元素并提取文本
- 选择具有特定 ID 的元素并提取文本
- 选择所有 <a> 标签并提取属性
- 选择所有具有特定类的列表项并提取文本
- 提取和修改输入框的值
- 修改第一个链接的 href 属性
- 修改段落的文本内容
- 操作元素的类属性(添加和移除类)
- 遍历 <body> 的子元素
- 查找包含特定文本的元素
- 添加新元素到 DOM
- 删除特定元素
- 修改输入元素的属性
- 提取 <style> 标签中的 CSS 内容
- 输出修改后的完整 HTML
示例输出:
Elements with class 'highlight':
- <H1>: Welcome to CsQuery
- <SPAN>: simple
Element with ID 'main-heading': Welcome to CsQuery
All <a> elements:
- Text: Visit Example.com, Href: https://example.com, Target: _blank
List items with class 'item':
- Item 1
- Item 2
- Item 3
Text Input Value: JohnDoe
Password Input Value:
First link href: https://example.com
Modified first link href: https://newexample.com
First paragraph text: This is a simple example.
Modified first paragraph HTML: This is an <strong>updated</strong> example.
Main heading classes: highlight
Main heading classes after adding 'new-class': highlight new-class
Main heading classes after removing 'highlight': new-class
Child elements of <body>:
- <H1>
- <P>
- <A>
- <UL>
- <INPUT>
- <INPUT>
Elements containing the text 'simple':
- <SPAN>: simple
After adding a new div:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="new-class">Welcome to CsQuery</h1>
<p>This is an <strong>updated</strong> example.</p>
<a href="https://newexample.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe" placeholder="Enter your username">
<input type="password" id="password">
<div class="new-div">This is a new div</div>
</body>
</html>
After removing the first list item:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="new-class">Welcome to CsQuery</h1>
<p>This is an <strong>updated</strong> example.</p>
<a href="https://newexample.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe" placeholder="Enter your username">
<input type="password" id="password">
<div class="new-div">This is a new div</div>
</body>
</html>
After setting placeholder for text input:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="new-class">Welcome to CsQuery</h1>
<p>This is an <strong>updated</strong> example.</p>
<a href="https://newexample.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe" placeholder="Enter your username">
<input type="password" id="password">
<div class="new-div">This is a new div</div>
</body>
</html>
Styles in <style> tag:
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
Modified HTML:
<!DOCTYPE html>
<html>
<head>
<title>CsQuery Example</title>
<style>
.highlight { color: yellow; }
#main { background-color: #f0f0f0; }
</style>
</head>
<body>
<h1 id="main-heading" class="new-class">Welcome to CsQuery</h1>
<p>This is an <strong>updated</strong> example.</p>
<a href="https://newexample.com" target="_blank">Visit Example.com</a>
<ul id="items">
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<input type="text" id="username" value="JohnDoe" placeholder="Enter your username">
<input type="password" id="password">
<div class="new-div">This is a new div</div>
</body>
</html>
9. 关键功能详解
1.选择元素
CsQuery 支持使用标准的 CSS 选择器来选择元素,类似于 jQuery 的选择器:
- 类选择器:.className
- ID 选择器:#idName
- 元素选择器:tagName
- 属性选择器:[attr='value']
- 组合选择器:parent > child, ancestor descendant, sibling + sibling 等
2.提取和修改属性
- 获取属性:
string href = link.GetAttribute("href"); 或 string href = link.Attr("href");
- 设置属性:
link.SetAttribute("href", "https://newexample.com"); 或 link.Attr("href", "https://newexample.com");
3.提取和修改文本内容
- 获取文本:
string text = element.Text();
- 设置文本:
element.Text("New Text Content");
- 获取和设置 HTML 内容:
string htmlContent = element.Html(); element.Html("<strong>Bold Text</strong>");
4.操作样式
虽然 CsQuery 本身不直接解析 CSS,但你可以通过操作 class 属性来间接控制元素的样式:
- 添加类:
element.AddClass("new-class");
- 移除类:
element.RemoveClass("highlight");
5.遍历和查询 DOM
- 遍历子元素:
var children = dom.Select("parentSelector").Children(); foreach (var child in children) { // 处理子元素 }
- 查找包含特定文本的元素:
var elements = dom.Select("*").Where(e => e.InnerText.Contains("specific text"));
6.添加和删除元素
- 添加新元素:
var newElement = CQ.Create("<div>New Element</div>").First(); dom.Select("body").Append(newElement);
- 删除元素:
element.Remove();
7.提取 <style> 标签中的 CSS
CsQuery 不解析 CSS,但你可以直接获取 <style> 标签中的内容:
var styles = dom.Select("style");
foreach (var style in styles)
{
string css = style.InnerText;
Console.WriteLine(css);
}
10. 注意事项
- 性能:CsQuery 在处理大型 HTML 文档时可能会有性能问题。对于非常复杂的文档,建议评估性能需求。
- 兼容性:CsQuery 模仿了 jQuery 的 API,但并不支持所有 jQuery 的功能,特别是那些依赖于浏览器环境的功能。
- CSS 选择器:虽然 CsQuery 支持大部分标准 CSS 选择器,但某些高级选择器或伪类选择器可能不被完全支持。
11. 总结
CsQuery 是一个强大且易于使用的 C# 库,适合需要类似 jQuery 的直观 API 来解析和操作 HTML 文档的场景。通过详细的示例,你可以看到如何利用 CsQuery 执行各种常见的 HTML 操作,如选择元素、提取和修改属性、操作文本内容、添加和删除元素等。
原文地址:https://blog.csdn.net/PLA12147111/article/details/142927810
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!