【发布时间】:2010-10-10 14:25:10
【问题描述】:
如何在 C# 中获取给定网址的 HTML 源代码?
【问题讨论】:
标签: c#
如何在 C# 中获取给定网址的 HTML 源代码?
【问题讨论】:
标签: c#
您可以使用WebClient class下载文件:
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");
}
【讨论】:
基本上:
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);
【讨论】:
最新的,最新的,最新的答案
这篇文章真的很老了(我回答的时候已经 7 岁了),所以没有使用其他答案新的推荐方式,即HttpClient class。
HttpClient 被认为是新的 API,它应该替换旧的 API(WebClient 和 WebRequest)
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;
}
}
有关如何使用HttpClient 类的更多信息(尤其是在异步情况下),您可以参考this question
注意 1:如果你想使用 async/await
string url = "page url";
HttpClient client = new HttpClient(); // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
注意 2:如果使用 C# 8 功能
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
【讨论】:
HttpClient 比WebClient 快得多。
您可以通过以下方式获取 HTML 源代码:
var html = new System.Net.WebClient().DownloadString(siteUrl)
【讨论】:
Dispose 是 WebClient 吗?
@cms 方法是较新的,在 MS 网站上建议,但我有一个很难解决的问题,两种方法都在这里发布,现在我将解决方案发布给大家!
问题:
如果您使用这样的网址:www.somesite.it/?p=1500 在某些情况下您会收到内部服务器错误 (500),
尽管在网络浏览器中,这 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");
//...
}
【讨论】: