我如何获取网页的内容并将其保存到字符串变量中

kam*_*001 70 c# asp.net screen-scraping

如何使用ASP.NET获取网页内容?我需要编写一个程序来获取网页的HTML并将其存储到字符串变量中.

dhi*_*esh 109

您可以使用WebClient

WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
Run Code Online (Sandbox Code Playgroud)

  • 没有投票,因为没有使用(WebClient客户端=新的WebClient()){} :) (12认同)
  • 这相当于斯蒂芬斯皮尔伯格的答案,在3分钟前发布,所以没有+1. (3认同)

Sco*_*ott 70

我以前遇到过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();
}
Run Code Online (Sandbox Code Playgroud)

  • @Greg,这是与性能相关的问题.我从来没有真正解决过它,但WebClient.DownloadString需要5-10秒才能下拉HTML,因为WebRequest/WebResponse几乎是立竿见影的.只是想提出另一种替代解决方案,以防OP出现类似问题或希望对请求/响应进行更多控制. (16认同)
  • @Scott - +1用于查找此内容.只是运行一些测试.DownloadString在首次使用时耗时更长(5299ms downloadstring vs 200ms WebRequest).在50 x BBC,50 x CNN和50 x另一个RSS Feed Urls的循环中测试它,使用不同的Urls来避免缓存.初始加载后,对于BBC,DownloadString快20ms,在CNN上快300ms.对于其他RSS提要,WebRequest快3毫秒.一般来说,我认为我将使用WebRequest for singles和DownloadString来循环访问URL. (6认同)
  • 你能详细说明你遇到的问题吗? (5认同)
  • 这对我来说非常合适,谢谢!为了节省其他人一点点搜索,WebRequest在System.Net中,Stream在System.Io中 (3认同)

use*_*674 24

我建议不要使用WebClient.DownloadString.这是因为(至少在.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();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 9

Webclient client = new Webclient();
string content = client.DownloadString(url);
Run Code Online (Sandbox Code Playgroud)

传递您想要获取的网页的网址.您可以使用htmlagilitypack解析结果.


Ji_*_*ing 5

我一直在使用 WebClient,但在发表这篇文章时(.NET 6 可用),WebClient 已被弃用。

首选方式是

HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);
Run Code Online (Sandbox Code Playgroud)

  • @NetXpert 我建议在声明它无用或不完整之前在 C# 交互式窗口中运行上面的代码块。我相信OP能够使用异步代码,因此代码片段没有被包装为返回Task<string>的异步函数。我已经用变量赋值更新了第二行以使其完整。 (3认同)