手机版 收藏 导航

在C#中如何抓取网页标题

原创   www.link114.cn   2023-08-26 15:47:53

在C#中如何抓取网页标题

using System;
using System.Net;
using System.Text;

string url = "https://www.example.com";
using (WebClient client = new WebClient())
{
    string html = client.DownloadString(url);
    int titleStart = html.IndexOf("<title>") + 7;
    int titleEnd = html.IndexOf("</title>");
    string title = html.Substring(titleStart, titleEnd - titleStart);
    Console.WriteLine("网页标题: " + title);
}
using System;
using System.Net;

string url = "https://www.example.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (System.IO.Stream stream = response.GetResponseStream())
{
    System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
    string html = reader.ReadToEnd();
    int titleStart = html.IndexOf("<title>") + 7;
    int titleEnd = html.IndexOf("</title>");
    string title = html.Substring(titleStart, titleEnd - titleStart);
    Console.WriteLine("网页标题: " + title);
}

这两种方法都可以有效地从网页中抓取标题信息。使用WebClient类的方法更加简单,而使用HttpWebRequest类的方法则更加灵活,可以设置更多的请求参数。开发者可以根据具体需求选择合适的方法。