阅读文章(首页/网页制作/HTML/JavaScript/)

两种分析HTML网页的方法

[日期:2005-12-23] 来源:不详  作者:佚名 [字体: ]

  有人想把Web Page拉下来并抽取其中的内容。这其实是搜索引擎的一项最最基本的工作:下载,抽取,再下载。我早年做过一个Search Engine项目,不过代码都已经不见了。这次有人又问到我这个事情,我给攒了两个方法。

  方法A,在一个WinForm里面用一个隐藏的Browser控件下载Web Page,并用IHTMLDocument来分析内容。这个方法比较简单,但如果对于大量文件的分析速度很慢。

  这个方法中用到的主要代码如下:
private void button1_Click(object sender, System.EventArgs e) {
 object url="
http://www.google.com";
 object nothing=null;
 this.axWebBrowser1.Navigate2(ref url,ref nothing,ref nothing,ref nothing,ref nothing);
 this.axWebBrowser1.DownloadComplete+=new System.EventHandler(this.button2_Click);
}

private void button2_Click(object sender, System.EventArgs e) {
 this.textBox1.Text="";
 msHTML.IHTMLDocument2 doc=(msHTML.IHTMLDocument2)this.axWebBrowser1.Document;
 msHTML.IHTMLElementCollection all=doc.all;
 System.Collections.IEnumerator enumerator=all.GetEnumerator();
 while(enumerator.MoveNext() && enumerator.Current!=null)
 {
  msHTML.IHTMLElement element=(msHTML.IHTMLElement)(enumerator.Current);
  if(this.checkBox1.Checked==true)
  {
   this.textBox1.Text+="\r\n\r\n"+element.innerHTML;
  }
  else
  {
   this.textBox1.Text+="\r\n\r\n"+element.outerHTML;
  }
 }
}

  方法B,用System.Net.WebClient下载Web Page存到本地文件或者String中用正则表达式来分析。这个方法可以用在Web Crawler等需要分析很多Web Page的应用中。

  下面是一个例子,能够把http://www.google.com首页里的所有的Hyperlink都抽取出来:

using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace HttpGet{
 class Class1{
  [STAThread]
  static void Main(string[] args){
   System.Net.WebClient client=new WebClient();
   byte[] page=client.DownloadData("
http://www.google.com");
   string content=System.Text.Encoding.UTF8.GetString(page);
   string regex="href=[\\\"
\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']";
   Regex re=new Regex(regex);
   MatchCollection matches=re.Matches(content);
   
   System.Collections.IEnumerator enu=matches.GetEnumerator();
   while(enu.MoveNext() && enu.Current!=null)
   {
    Match match=(Match)(enu.Current);
    Console.Write(match.Value+"\r\n");
   }
  }
 }
}

  真正做爬虫的,都是用正则表达式来做抽取的,可以找些开源的爬虫,代码都差不多。只是有些更高,可以把Flash或者javascript里面的URL都抽取出来。

  再补充一个,有人问我如果一个element是用document.write画出来的,还能不能在DOM里面取到。答案是肯定的。具体取的方法也和平常的一样。下面这个HTML就演示了从DOM里面取到用document.write动态生成的HTML Tag:






  点了“Click Me”以后,打印出来的forms[0]的子元素列表里面,“button 1”赫然在列。



阅读:
录入:

评论 】 【 推荐 】 【 打印
上一篇:用HTML编写应用程序
下一篇:HTML 标记总览
相关文章      
本文评论
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款