兩個分析HTML網頁的方法

 
 
有人想把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:

<form>
<SCRIPT>
   document.write("<input type=button id='btn1' value='button 1'>");
</SCRIPT>
<INPUT onclick=show() type=button value="click me">
</FORM>
<TEXTAREA id=allnode rows=29 cols=53></TEXTAREA>
<SCRIPT>
function show()
{
   document.all.item("allnode").innerText="";
   var i=0;
   for(i=0;i<document.forms[0].childNodes.length;i++)
   {
      document.all.item("allnode").innerText=document.all.item("allnode").innerText+"/r/n"+document.forms[0].childNodes[i].tagName+" "+document.forms[0].childNodes[i].value;
   }
}
</SCRIPT>


點了“Click Me”以後,打印出來的forms[0]的子元素列表裏面,“button 1”赫然在列。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章