在指定的URL下载内容
本文关键字:下载 URL | 更新日期: 2023-09-27 18:21:46
我只想从网站下载内容。最好的方法是什么?我已经尝试过WebClient
,但使用它我也可以获得所有的标签。我只想要内容。。
以下是我的代码:
WebClient w = new WebClient();
//Using DownloadString
string s = w.DownloadString("http://en.wikipedia.org/wiki/Main_Page");
Console.WriteLine(s);
//Using DownloadData
byte[] downloadedData = w.DownloadData("http://en.wikipedia.org/wiki/Main_Page");
string data = Encoding.ASCII.GetString(downloadedData);
Console.WriteLine(data);
有什么建议吗?
我想你想去掉下载的html并解析url的内容吗?
出于这些目的,我有一个静态类(在stackoverflow上找到):
public static class StringExtensions
{
public static string StripHTML(this string htmlString)
{
if (string.IsNullOrEmpty(htmlString)) return htmlString;
string pattern = @"<(.|'n)*?>";
string s = Regex.Replace(htmlString, pattern, string.Empty);
return s;
}
}
你可以这样使用它:
string s = SomeDownloadFunction("http://en.wikipedia.org/wiki/Main_Page");
string content = s.StripHTML();
虽然使用RegEx可以很容易地删除标记,但如果您想要检索页面上的所有实际内容(忽略广告、导航栏等),那真的是一项艰巨的任务。幸运的是,一些非常聪明的人很乐意分享他们在这方面的研究。看看锅炉管道(此处演示)。