Este artículo es un artículo espejo de traducción automática, por favor haga clic aquí para saltar al artículo original.

Vista: 22625|Respuesta: 0

[Fuente] C# Extraer y exportar todos los métodos de hipervínculos en la página web

[Copiar enlace]
Publicado en 15/7/2015 8:30:08 | | |
  1. public class app
  2.     {
  3.         // 获取指定网页的HTML代码
  4.         public static string GetPageSource(string URL)
  5.         {
  6.             Uri uri = new Uri(URL);

  7.             HttpWebRequest hwReq = (HttpWebRequest)WebRequest.Create(uri);
  8.             HttpWebResponse hwRes = (HttpWebResponse)hwReq.GetResponse();

  9.             hwReq.Method = "Get";

  10.             hwReq.KeepAlive = false;

  11.             StreamReader reader = new StreamReader(hwRes.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));

  12.             return reader.ReadToEnd();
  13.         }
  14.         // 提取HTML代码中的网址
  15.         public static ArrayList GetHyperLinks(string htmlCode)
  16.         {
  17.             ArrayList al = new ArrayList();

  18.             string strRegex = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";

  19.             Regex r = new Regex(strRegex, RegexOptions.IgnoreCase);
  20.             MatchCollection m = r.Matches(htmlCode);

  21.             for (int i = 0; i <= m.Count - 1; i++)
  22.             {
  23.                 bool rep = false;
  24.                 string strNew = m[i].ToString();

  25.                 // 过滤重复的URL
  26.                 foreach (string str in al)
  27.                 {
  28.                     if (strNew == str)
  29.                     {
  30.                         rep = true;
  31.                         break;
  32.                     }
  33.                 }

  34.                 if (!rep) al.Add(strNew);
  35.             }

  36.             al.Sort();

  37.             return al;
  38.         }
  39.         // 把网址写入xml文件
  40.         public static void WriteToXml(string strURL, ArrayList alHyperLinks)
  41.         {
  42.             XmlTextWriter writer = new XmlTextWriter("HyperLinks.xml", Encoding.UTF8);

  43.             writer.Formatting = Formatting.Indented;
  44.             writer.WriteStartDocument(false);
  45.             writer.WriteDocType("HyperLinks", null, "urls.dtd", null);
  46.             writer.WriteComment("提取自" + strURL + "的超链接");
  47.             writer.WriteStartElement("HyperLinks");
  48.             writer.WriteStartElement("HyperLinks", null);
  49.             writer.WriteAttributeString("DateTime", DateTime.Now.ToString());


  50.             foreach (string str in alHyperLinks)
  51.             {
  52.                 string title = GetDomain(str);
  53.                 string body = str;
  54.                 writer.WriteElementString(title, null, body);
  55.             }

  56.             writer.WriteEndElement();
  57.             writer.WriteEndElement();

  58.             writer.Flush();
  59.             writer.Close();
  60.         }

  61.         // 获取网址的域名后缀
  62.         static string GetDomain(string strURL)
  63.         {
  64.             string retVal;

  65.             string strRegex = @"(\.com/|\.net/|\.cn/|\.org/|\.gov/)";

  66.             Regex r = new Regex(strRegex, RegexOptions.IgnoreCase);
  67.             Match m = r.Match(strURL);
  68.             retVal = m.ToString();

  69.             strRegex = @"\.|/$";
  70.             retVal = Regex.Replace(retVal, strRegex, "").ToString();

  71.             if (retVal == "")
  72.                 retVal = "other";

  73.             return retVal;
  74.         }



  75.     }
Copiar código
  1. private void btnkaishi_Click(object sender, EventArgs e)
  2.         {
  3.             string strCode;
  4.             ArrayList alLinks;


  5.             if (txtapi.Text == "")
  6.             {
  7.                 MessageBox.Show("请输入网址");
  8.                 return;
  9.             }
  10.             string strURL = txtapi.Text.ToString().Trim();
  11.             if (strURL.Substring(0, 7) != @"http://")
  12.             {
  13.                 strURL = @"http://" + strURL;
  14.             }
  15.             MessageBox.Show("正在获取页面代码,请稍后...");
  16.             strCode = app.GetPageSource(strURL);
  17.             MessageBox.Show("正在提取超链接,请稍侯...");
  18.             alLinks = app.GetHyperLinks(strCode);
  19.             MessageBox.Show("正在写入文件,请稍侯...");
  20.             app.WriteToXml(strURL, alLinks);

  21.         }
Copiar código






Anterior:C# exporta el carácter de cadena al método de documento txt
Próximo:[Original] Baidu Active Push Tool v2.0 Descarga
Renuncia:
Todo el software, materiales de programación o artículos publicados por Code Farmer Network son únicamente para fines de aprendizaje e investigación; El contenido anterior no se utilizará con fines comerciales o ilegales; de lo contrario, los usuarios asumirán todas las consecuencias. La información de este sitio proviene de Internet, y las disputas de derechos de autor no tienen nada que ver con este sitio. Debes eliminar completamente el contenido anterior de tu ordenador en un plazo de 24 horas desde la descarga. Si te gusta el programa, por favor apoya el software genuino, compra el registro y obtén mejores servicios genuinos. Si hay alguna infracción, por favor contáctanos por correo electrónico.

Mail To:help@itsvse.com