使用HttpWebRequest获取任何网页的内容…
// We will store the html response of the request here
string siteContent = string.Empty;
// The url you want to grab
string url = "";
// Here we're creating our request, we haven't actually sent the request to the site yet...
// we're simply building our HTTP request to shoot off to google...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
// Right now... this is what our HTTP Request has been built in to...
/*
GET / HTTP/1.1
Host:
Accept-Encoding: gzip
Connection: Keep-Alive
*/
// Wrap everything that can be disposed in using blocks...
// They dispose of objects and prevent them from lying around in memory...
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) // Go query google
using(Stream responseStream = response.GetResponseStream()) // Load the response stream
using(StreamReader streamReader = new StreamReader(responseStream)) // Load the stream reader to read the response
{
siteContent = streamReader.ReadToEnd(); // Read the entire response and store it in the siteContent variable
}
// magic...
Console.WriteLine (siteContent);
如果觉得《asp.net 抓取html内容 c# – 如何从ASP.NET获取网页的HTML内容》对你有帮助,请点赞、收藏,并留下你的观点哦!