2012-05-09 13 views
5

いいから、テーブルからデータを取得するにはライブWebサイトを照会する必要があります。このHTMLテーブルをDataTableに入れてからこのデータを使用します。私は今までHtml Agility PackとXPathを使用してテーブルの各行にアクセスしていましたが、DataTableに解析する方法が必要であることは知っています。 (C#の)私は現在使用しているコードは次のとおりです。HTMLテーブルからデータテーブルにデータを取得する

string htmlCode = ""; 
using (WebClient client = new WebClient()) 
{ 
htmlCode = client.DownloadString("http://www.website.com"); 
} 
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 

doc.LoadHtml(htmlCode); 

//My attempt at LINQ to solve the issue (not sure where to go from here) 
var myTable = doc.DocumentNode 
.Descendants("table") 
.Where(t =>t.Attributes["summary"].Value == "Table One") 
.FirstOrDefault(); 

//Finds all the odd rows (which are the ones I actually need but would prefer a 
//DataTable containing all the rows! 
foreach (HtmlNode cell in doc.DocumentNode.SelectNodes("//tr[@class='odd']/td")) 
{ 
string test = cell.InnerText; 
//Have not gone further than this yet! 
} 

HTMLテーブルのウェブサイト上で私はこのようなルックスを照会しています:私はそれがが容易/優れているかどうかわからないんだけど

<table summary="Table One"> 
<tbody> 
<tr class="odd"> 
<td>Some Text</td> 
<td>Some Value</td> 
</tr> 
<tr class="even"> 
<td>Some Text1</td> 
<td>Some Value1</td> 
</tr> 
<tr class="odd"> 
<td>Some Text2</td> 
<td>Some Value2</td> 
</tr> 
<tr class="even"> 
<td>Some Text3</td> 
<td>Some Value3</td> 
</tr> 
<tr class="odd"> 
<td>Some Text4</td> 
<td>Some Value4</td> 
</tr> 
</tbody> 
</table> 

希望の結果を得るためにLINQ + HAPまたはXPath + HAPを使用すると、おそらく見ることができるように、私は両方とも限定的な成功を収めました。これは私がこれまでにウェブサイトを検索したり、ウェブサイトとのやりとりをするプログラムを作ったのは初めてです。事前に助けていただきありがとうございます:)

+0

これは役に立ちますか? http://weblogs.asp.net/grantbarrington/archive/2009/10/15/screen-scraping-in-c.aspx – iwayneo

答えて

4

HTMLアジリティパックのような方法はありませんが、作成するのは難しいことではありません。 Linq-to-XMLからDatatableにXMLを行うsamples out thereがあります。これらは必要なものに再加工できます。

私は方法全体を作成するのに役立ちますが、今日はそうではありません:)。

も参照してください:

+0

これらのリソースを見ていただき、ありがとうございましたそれを行う方法:D –

+0

他人のためにあなたのソリューションを共有してもよろしいですか? – jessehouwing

+0

下記のチップをお買い上げいただきありがとうございます! –

3

これは私のソリューションです。少し厄介かもしれないが、それは現時点では完全に働いている:D

string htmlCode = ""; 
using (WebClient client = new WebClient()) 
{ 
client.Headers.Add(HttpRequestHeader.UserAgent, "AvoidError"); 
htmlCode = client.DownloadString("http://www.website.com"); 
} 
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 

doc.LoadHtml(htmlCode); 

DataTable dt = new DataTable(); 
dt.Columns.Add("Name", typeof(string)); 
dt.Columns.Add("Value", typeof(decimal)); 

int count = 0; 
decimal rowValue = 0; 
bool isDecimal = false; 
foreach (var row in doc.DocumentNode.SelectNodes("//table[@summary='Table Name']/tbody/tr")) 
{ 
DataRow dr = dt.NewRow(); 
foreach (var cell in row.SelectNodes("td")) 
{ 
if ((count % 2 == 0)) 
{ 
dr["Name"] = cell.InnerText.Replace("&nbsp;", " "); 
} 
else 
{ 
isDecimal = decimal.TryParse((cell.InnerText.Replace(".", "")).Replace(",", "."), out rowValue); 
if (isDecimal) 
{ 
dr["Value"] = rowValue; 
} 
dt.Rows.Add(dr); 
} 
count++; 
} 
} 
8

ジャックエケルの上記のコードとマークGravell(see post here)からいくつかのコードの一部を使用して、私は解決策に来ることができました。 このコードスニペットは、データテーブルにHTMLテーブルを変換するためにシンプルなロジック

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Web; 
using System.Net; 
using HtmlAgilityPack; 



namespace WindowsFormsApplication 
{ 
    public partial class Form1 : Form 
    { 
     private DataTable dt; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

      string htmlCode = ""; 
      using (WebClient client = new WebClient()) 
      { 
       client.Headers.Add(HttpRequestHeader.UserAgent, "AvoidError"); 
       htmlCode = client.DownloadString("http://www.info.gov.za/aboutsa/holidays.htm"); 
      } 
      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 

      doc.LoadHtml(htmlCode); 

      dt = new DataTable(); 
      dt.Columns.Add("Name", typeof(string)); 
      dt.Columns.Add("Value", typeof(string)); 

      int count = 0; 


      foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) 
      { 

       foreach (HtmlNode row in table.SelectNodes("tr")) 
       { 

        if (table.Id == "table2") 
        { 
         DataRow dr = dt.NewRow(); 

         foreach (var cell in row.SelectNodes("td")) 
         { 
          if ((count % 2 == 0)) 
          { 
           dr["Name"] = cell.InnerText.Replace("&nbsp;", " "); 
          } 
          else 
          { 

           dr["Value"] = cell.InnerText.Replace("&nbsp;", " "); 

           dt.Rows.Add(dr); 
          } 
          count++; 

         } 


        } 

       } 


       dataGridView1.DataSource = dt; 

      } 
     } 

    } 
} 
1

この記事を書いているとして、南アフリカで2012年の祝日を取得するために使用されています。あなたが試すことができ

//Define your webtable 
public static HtmlTable table 
      { 
       get 
       { 
        HtmlTable var = new HtmlTable(parent); 
        var.SearchProperties.Add("id", "searchId"); 
        return var; 
       } 
      } 

//Convert a webtable to datatable 
public static DataTable getTable 
      { 
       get 
       { 
        DataTable dtTable= new DataTable("TableName"); 
        UITestControlCollection rows = table.Rows; 
        UITestControlCollection headers = rows[0].GetChildren(); 
        foreach (HtmlHeaderCell header in headers) 
        { 
         if (header.InnerText != null) 
          dtTable.Columns.Add(header.InnerText); 
        } 
        for (int i = 1; i < rows.Count; i++) 
        { 
         UITestControlCollection cells = rows[i].GetChildren(); 
         string[] data = new string[cells.Count]; 
         int counter = 0; 
         foreach (HtmlCell cell in cells) 
         { 
          if (cell.InnerText != null) 
           data[counter] = cell.InnerText; 
          counter++; 
         } 
         dtTable.Rows.Add(data); 
        } 
        return dtTable; 
       } 
      } 
0

DataTable.Rows[i].Cells[j].InnerText; 

ここで、DataTableはテーブルのIDです.iは行、jはセルです。

関連する問題