2011-03-17 94 views
1

昨晚當我問起屏幕抓取時,我獲得了一篇很好的文章鏈接,並且讓我注意到了這一點。然而,我有幾個問題。我將發佈我的代碼以及下面的html源代碼。我試圖抓住數據表之間的數據,然後將數據發送到一個sql表。我已經找到了成功抓取描述部件3.5 ect ...最後修改由喬然而,因爲第1 2/tr還包含img src =/......「alt =」00721408「數字不抓住。我堅持要如何改變代碼,以便抓取表中的所有數據。第二,爲了準備將數據發送到sql表,我需要做什麼。我的代碼如下:HTMLAgility幫助屏幕抓取

using System; 
     using System.Collections.Generic; 
     using System.Linq; 
     using System.Text; 
     using HtmlAgilityPack; 
     using System.Windows.Forms; 

     namespace ConsoleApplication1 
     { 

     } 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       // Load the html document 
       var webGet = new HtmlWeb(); 
       var doc = webGet.Load("http://localhost"); 

       // Get all tables in the document 
       HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table"); 

       // Iterate all rows in the first table 
       HtmlNodeCollection rows = tables[0].SelectNodes(".//tr"); 
       for (int i = 0; i < rows.Count; ++i) 
       { 
        // Iterate all columns in this row 
        HtmlNodeCollection cols = rows[i].SelectNodes(".//td"); 
        for (int j = 0; j < cols.Count; ++j) 
        { 

         // Get the value of the column and print it 
         string value = cols[j].InnerText; 

         Console.WriteLine(value); 


        } 
       } 

      } 
     } 





<table class="data"> 




<tr><td>Part-Num</td><td width="50"></td><td><img src="/partcode/number/072140" alt="072140"/></td></tr> 




<tr><td>Manu-Number</td><td width="50"></td><td><img src="/partcode/manu/00721408" alt="00721408" /></td></tr> 

<tr><td>Description</td><td></td><td>Widget 3.5</td></tr> 



<tr><td>Manu-Country</td><td></td><td>United States</td></tr> 

<tr><td>Last Modified</td><td></td><td>26 Jan 2011, 8:08 PM</td></tr> 


<tr><td>Last Modified By</td><td></td><td> 
Manu 

</td></tr> 




</table> 



<p> 


</body></html> 

回答

0

雖然脆弱的像這樣的工作,你的情況 - 基本上就是包括所有圖像alt屬性的文本內容:

// Iterate all rows in the first table 
HtmlNodeCollection rows = tables[0].SelectNodes(".//tr"); 
for (int i = 0; i < rows.Count; ++i) 
{ 
    // Iterate all columns in this row 
    HtmlNodeCollection cols = rows[i].SelectNodes(".//td"); 
    for (int j = 0; j < cols.Count; ++j) 
    { 
     var images = cols[j].SelectNodes("img"); 
     if(images!=null) 
      foreach (var image in images) 
      { 
       if(image.Attributes["alt"]!=null) 
        Console.WriteLine(image.Attributes["alt"].Value); 
      } 
     // Get the value of the column and print it 
     string value = cols[j].InnerText; 
     Console.WriteLine(value); 
    } 
} 
+0

謝謝我將使用這個想法 – JRB 2011-03-17 04:35:57

0

我很困惑豆蔻,以什麼數據,你「重新嘗試但獲得...

你可以嘗試:

的SelectNodes( 「// TD [文本()= '說明'] /../孩子:: * [3]」)

,其內的文本應該是 「窗口小部件3.5」

的SelectNodes( 「// TD [文本()= '馬努國'] /../子:: * [3]」)

其內文應爲「美國」

等等

順便說一句,作爲一個無恥的插件,你應該看看:systemhtml.codeplex.com 它是另一個html解析器。

+0

我會看看systemhtml。是的,你是正確的我想採取內部文本「小部件3.5美國等,並將其發送到一個SQL表格與字段說明,馬努國家等。 – JRB 2011-03-17 03:12:23