如何使用ASP.NET獲取網頁的內容?我需要編寫一個程序來獲取網頁的HTML並將其存儲到字符串變量中。如何獲取網頁內容並將其保存到字符串變量中
61
A
回答
94
可以使用WebClient
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
7
Webclient client = new Webclient();
string content = client.DownloadString(url);
通過你想要得到的頁面的URL。你可以使用htmlagilitypack來分析結果。
62
我已經與Webclient.Downloadstring之前遇到的問題。使用WebClient.DownloadString
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
19
我建議不:如果你這樣做,你可以試試這個。這是因爲(至少在.NET 3.5中)DownloadString不夠聰明,可以使用/刪除BOM,如果它存在。這會導致BOM(
)在返回UTF-8數據時(至少沒有字符集)錯誤地作爲字符串的一部分顯示 - ick!
相反,這種輕微變化將正確地工作的材料明細表:
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
不幸的是DownloadString(截至.NET 3.5)是不夠聰明與物料清單的工作。我在答覆中加入了一個替代方案。 – user2246674 2013-05-04 00:13:56
沒有投票,因爲沒有使用(WebClient客戶端=新的WebClient()){} :) – 2013-07-15 04:24:01