在C#中检索网页HTML内容可以通过使用HttpClient类和HtmlAgilityPack库来实现。
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("https://www.example.com");
response.EnsureSuccessStatusCode();
string htmlContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(htmlContent);
}
}
}
using System;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
HtmlWeb web = new HtmlWeb();
HtmlDocument document = web.Load("https://www.example.com");
HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//div[@class='content']");
if (nodes != null)
{
foreach (HtmlNode node in nodes)
{
Console.WriteLine(node.InnerHtml);
}
}
}
}
以上代码示例中,我们使用HttpClient类发送GET请求获取网页的HTML内容,并使用HtmlAgilityPack库解析HTML文档并检索特定的节点内容。
推荐的腾讯云相关产品:腾讯云服务器(https://cloud.tencent.com/product/cvm)和腾讯云CDN(https://cloud.tencent.com/product/cdn)。腾讯云服务器提供了可靠的云计算基础设施,可用于部署和运行C#应用程序。腾讯云CDN可以加速网页内容的传输,提高网页加载速度。
领取专属 10元无门槛券
手把手带您无忧上云