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
类的方法则更加灵活,可以设置更多的请求参数。开发者可以根据具体需求选择合适的方法。