【发布时间】:2011-05-29 10:54:49
【问题描述】:
如何使用 ASP.NET 获取网页内容?我需要编写一个程序来获取网页的 HTML 并将其存储到字符串变量中。
【问题讨论】:
标签: c# asp.net screen-scraping
如何使用 ASP.NET 获取网页内容?我需要编写一个程序来获取网页的 HTML 并将其存储到字符串变量中。
【问题讨论】:
标签: c# asp.net screen-scraping
Webclient client = new Webclient();
string content = client.DownloadString(url);
传递您想要获取的页面的 URL。您可以使用 htmlagilitypack 解析结果。
【讨论】:
您可以使用WebClient
Using System.Net;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
【讨论】:
我之前遇到过 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();
}
【讨论】:
我建议不要使用WebClient.DownloadString。这是因为(至少在 .NET 3.5 中)DownloadString 不够聪明,无法使用/删除 BOM,如果它存在的话。这可能会导致 BOM (@ 987654322@) 在返回 UTF-8 数据时错误地显示为字符串的一部分(至少没有字符集)- ick!
相反,这种细微的变化将在 BOM 中正常工作:
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();
}
}
【讨论】: