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


108

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

Answers:


184

您可以使用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");
}

应该注意:如果需要更多控制,请查看HttpWebRequest类(例如,能够指定身份验证)。
理查德

1
是的,尽管您可以使用client.UploadData(uriString,“ POST”,postParamsByteArray);与WebClient进行POST请求,但是HttpWebRequest可以为您提供更多控制权。
CMS

1
捕获WebException是不是很谨慎?也许是假设的。此方法是否需要捕获其他任何异常或错误?
约翰·沃斯塔姆2014年

4
@JohnWasham-是的,在这里捕获异常会很谨慎。值得庆幸的是,大多数StackOverflow受访者都将示例代码保持得尽可能简洁明了。使示例代码更接近“现实生活”只会增加噪音。
克里斯·罗杰斯

我面临的问题是,当我下载pagesource并获取数据时,而不是该网站使用其他语言而不是pagesource时,并没有获得这些值
Rush.2707,2016年

40

基本上:

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

19

最新,最新的答案
这篇文章确实很老(我回答时已经7岁了),因此其他答案中没有一个使用新的推荐方法,即HttpClient上课。


HttpClient被认为是新的API,并且应替换旧的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;
   }
}

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


4
建议:等待异步方法。
Maarten

@Maarten以下链接展示了如何使用这跟异步/ AWAIT stackoverflow.com/questions/33020657/...
哈坎Fıstık

17

您可以通过以下方式获得它:

var html = new System.Net.WebClient().DownloadString(siteUrl)

简短而甜蜜!在阅读乔·阿尔巴哈里的榜样后,我发现了您的建议。LINQPad>帮助>新增功能,然后搜索缓存。
科林

7
var html = new System.Net.WebClient()。DownloadString(siteUrl); //需要更新您的客户!
user1328350 2014年

9
DisposeWebClient吗?
JD

11

MS网站上建议使用@cms方法,但是我有一个很难解决的问题,两种方法都发布在这里,现在我发布所有解决方案!

问题: 如果您使用这样的网址: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");
    //...
}

这里的官方文件

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.