如何在C#中下载HTML源代码?

Not*_*Dan 102 c#

如何在c#中获取给定网址的HTML源代码?

CMS*_*CMS 178

您可以使用WebClient类下载文件:

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}
Run Code Online (Sandbox Code Playgroud)

  • @JohnWasham - 是的,在这里捕捉例外是谨慎的.值得庆幸的是,大多数StackOverflow响应者都将示例代码尽可能简洁明了.使示例代码更接近"现实生活"只会增加噪音. (4认同)

Die*_*cic 39

基本上:

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);
Run Code Online (Sandbox Code Playgroud)


Xen*_*non 17

你可以得到它:

var html = new System.Net.WebClient().DownloadString(siteUrl)
Run Code Online (Sandbox Code Playgroud)

  • var html = new System.Net.WebClient().DownloadString(siteUrl); //需要新客户! (7认同)
  • 那个`Dispose``WebClient`? (6认同)

Hak*_*tık 16

这篇文章真的很老了(当我回答它时已经7岁了),所以没有其他解决方案使用新的和推荐的方式,即HttpClient类.

HttpClient被认为是新的API,它应该取代旧的(WebClientWebRequest)

string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
   using (HttpContent content = response.Content)
   {
      string result = content.ReadAsStringAsync().Result;
   }
}
Run Code Online (Sandbox Code Playgroud)

有关如何使用HttpClient该类的更多信息(特别是在异步情况下),您可以参考此问题

  • 建议:等待异步方法。 (2认同)

Xil*_*iki 11

@cms的方式是最新的,在MS网站上建议,但是我有一个难以解决的问题,这两个方法都贴在这里,现在我发布所有的解决方案!

问题: 如果您使用这样的URL:www.somesite.it/?p=1500在某些情况下,您会收到内部服务器错误(500),尽管在Web浏览器中这www.somesite.it/?p=1500完全有效.

解决方案: 你必须移出参数(是的很容易),工作代码是:

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}
Run Code Online (Sandbox Code Playgroud)

这里是官方文件