【问题标题】:filter links on page web by files extensions按文件扩展名过滤网页网页上的链接
【发布时间】:2017-06-18 03:09:15
【问题描述】:

我正在开发从网页中提取链接并使用 HtmlAgilityPack 过滤它们的程序

HtmlWeb hw = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc = hw.Load(txt_url.Text);
        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("a//[@href]"))
        {
            // Get the value of the HREF attribute
            string hrefValue = link.GetAttributeValue("href", string.Empty);
            listbox1.Items.Add(hrefValue);

        }

此代码正在从网页中提取所有链接,所以我的问题是如何通过“.html”等扩展名过滤这些 URL

【问题讨论】:

    标签: c# html html-agility-pack


    【解决方案1】:

    使用WebClient.DownloadString方法获取html。

    然后在字符串上使用正则表达式模式来捕获所有 URL。

    【讨论】:

      【解决方案2】:

      首先,您必须执行 HTTP GET 请求并使用 HTML 代码获取响应正文。

      //Request HTTP GET
      
      ServicePointManager.Expect100Continue = false;
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
      request.Proxy = null;
      request.Method = "GET";
      
      WebResponse response;
      string html = "";
      
      response = request.GetResponse();
      StreamReader sr = new StreamReader(response.GetResponseStream());
      html = sr.ReadToEnd();
      sr.Close();
      response.Close();
      

      然后您可以使用正则表达式解析 HTML 代码以提取所需的文件。

      【讨论】:

        猜你喜欢
        • 2014-12-14
        • 2011-04-02
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-11
        • 1970-01-01
        • 2010-12-31
        相关资源
        最近更新 更多