2016-07-20 81 views
0

在這個Html代碼中,我需要從html標籤中獲取屬性和數據。這是一個例子:使用HtmlAgillityPack如何獲取數據和屬性的HTML標籤?

...

<tr class="first-row"><td class="first-cell tl"><a href="../matchdetails.php?matchid=MaxATAKK" onclick="win(this.href, 560, 500, 0, 1); return false;">Gefle - Kalmar</a></td><td class="result"><a href="../matchdetails.php?matchid=MaxATAKK" onclick="win(this.href, 560, 500, 0, 1); return false;">4:2</a></td><td class="odds best-betrate" data-odd="3.53"></td><td class="odds" data-odd="3.37"></td><td class="odds" data-odd="2.04"></td><td class="last-cell nobr date">18.07.2016</td></tr> 

...

所以,我需要得到TD標記和屬性之間的數據(數據奇)。

這是我的C#代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using HtmlAgilityPack; 

namespace bexscraping 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      string url = "http://www.betexplorer.com/soccer/sweden/allsvenskan/results/"; 
      HtmlWeb web = new HtmlWeb(); 
      HtmlAgilityPack.HtmlDocument doc = web.Load(url); 
      foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//table")) 
      { 

       //node.Remove(); 

       outputLabel.Text += node.InnerText; 
      } 



     } 

    } 

} 

什麼建議嗎?謝謝!

+0

嘗試濾波「賠率」。 – CiccioRocca

+0

謝謝,你有一些鏈接,或者你能給我一個例子嗎?再次感謝! – Marci

回答

1

這是一些Msdn示例:XPath Examples; XPath Reference

根據您的片斷,你可以選擇所有標籤TD包含屬性數據奇。 .SelectNodes( 「// TD [@class =」 「賠率」, 「]」)這一點,因爲文檔的XPath表示,選擇所有節點TD包含一個屬性 「類」 等於:使用XPath

private void Form1_Load(object sender, EventArgs e) 
{ 

     string url = "http://www.betexplorer.com/soccer/sweden/allsvenskan/results/"; 
     HtmlWeb web = new HtmlWeb(); 
     HtmlAgilityPack.HtmlDocument doc = web.Load(url); 
     var nodes = doc.DocumentNode.SelectNodes("//td[@data-odd]"); 
     foreach (HtmlNode node in nodes) 
     { 
      //Here process your node 
      //Example: to get data-odd value 
      var val = node.GetAttributeValue("data-odd", ""); 
     } 
} 
+0

感謝您的支持。我嘗試了它,但我得到了一個錯誤消息:「名稱可能性在當前上下文中不存在」。怎麼了?再次感謝 – Marci

+0

@Marci對不起,我測試了代碼,但我複製的不好。我更新答案。只是不是賠率(0),但節點。 – CiccioRocca

+0

我嘗試了你的修正,但我得到了另一個錯誤,或多或少是這樣的:HtmlAgilityPack.HtmlAttributeCollection'不包含'項目'的定義,並沒有找到沒有擴展方法'Item'接受類型'HtmlAgilityPack的第一個參數。 HtmlAttributeCollection'。可能缺少使用指令或對程序集的引用。 – Marci