打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#提取网页中的超链接
using System;
  using System.Xml;
  using System.Text;
  using System.Net;
  using System.IO;
  using System.Collections;
  using System.Text.RegularExpressions;
  public class App
  {
   public static void Main()
   { 
   string strCode;
   ArrayList alLinks;
   Console.Write("请输入一个网页地址:");
   string strURL = Console.ReadLine();
   if(strURL.Substring(0,7) != @"http://")
   {
    strURL = @"http://" + strURL;
   }
    Console.WriteLine("正在获取页面代码,请稍侯...");
   strCode = GetPageSource(strURL);
    Console.WriteLine("正在提取超链接,请稍侯...");
   alLinks = GetHyperLinks(strCode);
    Console.WriteLine("正在写入文件,请稍侯...");
   WriteToXml(strURL,alLinks);
   }
  // 获取指定网页的HTML代码
   static string GetPageSource(string URL)
   {
   Uri uri =new Uri(URL);
    HttpWebRequest hwReq = (HttpWebRequest)WebRequest.Create(uri);
   HttpWebResponse hwRes = (HttpWebResponse)hwReq.GetResponse();
    hwReq.Method = "Get";
    hwReq.KeepAlive = false;
    StreamReader reader = new StreamReader(hwRes.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312"));
    return reader.ReadToEnd();
  }
      // 提取HTML代码中的网址
   static ArrayList GetHyperLinks(string htmlCode)
   {
   ArrayList al = new ArrayList();
    string strRegex = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
     Regex r = new Regex(strRegex,RegexOptions.IgnoreCase);
   MatchCollection m = r.Matches(htmlCode);
    for(int i=0; i<=m.Count-1; i++)
   {
    bool rep = false;
    string strNew = m[i].ToString();
     // 过滤重复的URL
    foreach(string str in al)
    {
    if(strNew==str)
    {
     rep =true;
     break;
    } 
    }
   if(!rep) al.Add(strNew);
  }
  al.Sort();
  return al;
  }
      // 把网址写入xml文件
   static void WriteToXml(string strURL, ArrayList alHyperLinks)
   {
   XmlTextWriter writer = new XmlTextWriter("HyperLinks.xml",Encoding.UTF8);
   writer.Formatting = Formatting.Indented;
   writer.WriteStartDocument(false);
   writer.WriteDocType("HyperLinks", null, "urls.dtd", null);
   writer.WriteComment("提取自" + strURL + "的超链接");
   writer.WriteStartElement("HyperLinks");
   writer.WriteStartElement("HyperLinks", null);
   writer.WriteAttributeString("DateTime",DateTime.Now.ToString());
   foreach(string str in alHyperLinks)
   {
    string title = GetDomain(str);
    string body = str;
    writer.WriteElementString(title,null,body);
   }
  writer.WriteEndElement();
   writer.WriteEndElement();
  writer.Flush();
   writer.Close();
   }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
河南省再次痛失名牌大学,历史悲剧再次重演
我的空中摄影美图展示(22)
经典搞笑糗事爆笑笑话,今天在老婆面前唱了首歌,结果被老婆暴揍一顿!
既强壮心脉,又畅通心脉,奇妙的中成药
德国纪录片《鸟瞰俄罗斯》全5集合集
用甲硝唑治疗痔疮的方法
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服