900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > asp.net 抓取html内容 c# – 如何从ASP.NET获取网页的HTML内容

asp.net 抓取html内容 c# – 如何从ASP.NET获取网页的HTML内容

时间:2021-05-02 19:58:22

相关推荐

asp.net 抓取html内容 c# – 如何从ASP.NET获取网页的HTML内容

使用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);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。