在下载的txt文件中提取url链接

时间:2015-12-29 15:54:40

标签: c# html regex url

目前正在处理一个url提取器进行工作。我试图从下载的html文件中提取所有http链接/ href链接,并在单独的txt文件中打印自己的链接。到目前为止,我已设法将页面的整个html下载到其中只是从中提取链接并使用Regex打印它们是一个问题。想知道是否有人可以帮我这个?

     private void button2_Click(object sender, EventArgs e)
    {
        Uri fileURI = new Uri(URLbox2.Text);

        WebRequest request = WebRequest.Create(fileURI);
        request.Credentials = CredentialCache.DefaultCredentials;
        WebResponse response = request.GetResponse();
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();

        SW = File.CreateText("C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\response1.htm");
        SW.WriteLine(responseFromServer);

        SW.Close();

        string text = System.IO.File.ReadAllText(@"C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\response1.htm");
        string[] links = System.IO.File.ReadAllLines(@"C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\response1.htm");



        Regex regx = new Regex(links, @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

        MatchCollection mactches = regx.Matches(text);

        foreach (Match match in mactches)
        {
            text = text.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
        }

        SW = File.CreateText("C:\\Users\\Conal_Curran\\OneDrive\\C#\\MyProjects\\Web Crawler\\URLTester\\Links.htm");
        SW.WriteLine(links);
    }

1 个答案:

答案 0 :(得分:3)

如果您不知道,可以使用其中一个可用的html解析器nuget包来实现(非常容易)。

我个人使用 HtmlAgilityPack (以及 ScrapySharp ,另一个包)和 AngleSharp

上面只有3行,你使用HtmlAgilityPack来获取http get请求加载的文档中的所有href:

/*
  do not forget to include the usings:
  using HtmlAgilityPack;
  using ScrapySharp.Extensions;
*/

HtmlWeb w = new HtmlWeb();
//since you have your html locally stored, you do the following:

//P.S: By prefixing file path strings with @, you are rid of having to escape slashes and other fluffs.
var doc = HtmlDocument.LoadHtml(@"C:\Users\Conal_Curran\OneDrive\C#\MyProjects\Web Crawler\URLTester\response1.htm");

//for an http get request
//var doc = w.Load("yourAddressHere");
var hrefs = doc.DocumentNode.CssSelect("a").Select(a => a.GetAttributeValue("href"));