如何獲取在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. 如何下載Chromium源代碼?
- 7. 如何通過git下載源代碼?
- 8. 如何下載BIRT的源代碼?
- 9. 如何僅下載Android ICS源代碼
- 10. 如何下載網站的源代碼
- 11. 如何下載GCC源代碼?
- 12. 如何下載code.google.com的源代碼
- 13. 如何下載wordpress源代碼?
- 14. 如何下載此源代碼文件?
- 15. 如何下載Eclipse的源代碼?
- 16. 如何從code.google.com下載源代碼
- 17. 如何使用bazaar下載源代碼?
- 18. 如何從源代碼下載頁面
- 19. WSO2 ESB如何下載源代碼
- 20. 如何下載cryengine V的源代碼?
- 21. 如何下載Cassini Webserver的源代碼?
- 22. 如何下載aptoide的源代碼?
- 23. 下載html源碼android?
- 24. 如何使用RoboSpice下載html源代碼?
- 25. 如何自動下載網站的html源代碼
- 26. 如何從HTML源代碼下載所有鏈接的圖像?
- 27. 在TreeView C#中的HTML源代碼#
- 28. 在Trac中下載源代碼
- 29. 如何從html網格下載excel或CVS文件在我的c#代碼
- 30. 在angularjs中生成的表單下載html代碼的源代碼
應該注意:如果需要更多控制,請查看HttpWebRequest類(例如,能夠指定身份驗證)。 – Richard 2009-03-01 15:12:16
是的,儘管你可以使用WebClient,使用client.UploadData(uriString,「POST」,postParamsByteArray)來執行POST請求,但HttpWebRequest爲你提供了更多的控制。 – CMS 2009-03-01 17:51:31