如何获取在c#中给定网址的HTML源代码?我如何在C#中下载HTML源代码?
87
A
回答
155
您可以用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");
//...
}
33
基本上是:
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);
10
“CMS” 的方式是比较近的,建议在MS网站
,但我有一个问题很难解决,宽度两个方法张贴在这里
现在我post solu所有!
问题: 如果使用这样的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");
//...
}
这里官方文档: http://msdn.microsoft.com/en-us/library/system.net.webclient.querystring.aspx
13
你可以得到它:
var html = new System.Net.WebClient().DownloadString(siteUrl)
4
这篇文章真的很老了(当我7岁的时候回答它),所以没有其他解决方案使用新的推荐方式,即HttpClient
类。
HttpClient
被认为是新的API,它应该替换旧WebClient
和WebRequest
string url = "page url";
using (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. 我该如何下载Android源代码
- 2. 如何在我的应用程序中下载Instagram页面的HTML源代码
- 3. 使用GWT下载html页源代码
- 4. 下载html源代码很慢
- 5. 源代码html没有完整下载
- 6. 如何下载GCC源代码?
- 7. 如何仅下载Android ICS源代码
- 8. 如何从code.google.com下载源代码
- 9. 如何下载BIRT的源代码?
- 10. 如何下载此源代码文件?
- 11. 如何使用bazaar下载源代码?
- 12. 如何下载Eclipse的源代码?
- 13. 如何通过git下载源代码?
- 14. 如何从源代码下载页面
- 15. 如何下载cryengine V的源代码?
- 16. 如何下载Cassini Webserver的源代码?
- 17. 下载html源码android?
- 18. 如何从HTML源代码下载所有链接的图像?
- 19. 在Trac中下载源代码
- 20. 如何从html网格下载excel或CVS文件在我的c#代码
- 21. 如何在Windows Phone中下载html源代码和网页内容?
- 22. 安卓:下载源代码
- 23. 下载Eclipse的源代码
- 24. Android源代码下载
- 25. 谷歌代码下载源
- 26. 如何在不下载源代码的情况下使用EXSLT?
- 27. 如何下载Android源代码并在Eclipse中连接它?
- 28. 如何在IDEA中下载特定Maven工件的源代码?
- 29. 如何下载此源码?
- 30. 如何下载android源码?
应该注意:如果需要更多控制,请查看HttpWebRequest类(例如,能够指定身份验证)。 – Richard 2009-03-01 15:12:16
是的,尽管你可以使用WebClient,使用client.UploadData(uriString,“POST”,postParamsByteArray)来执行POST请求,但HttpWebRequest为你提供了更多的控制。 – CMS 2009-03-01 17:51:31