Marci
Marci

Reputation: 319

Using HtmlAgillityPack how can get data and attributes HTML tags?

In this Html code I need to get attributes and data from html tags. This is an example:

...

   <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>

...

So, I need to get data between td tags and attributes (data-odd).

This is my C# code:

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;
            }



        }

    }

}

Any suggestion? Thanks!

Upvotes: 0

Views: 1138

Answers (1)

Babbillumpa
Babbillumpa

Reputation: 1864

Here it is some Msdn Examples: XPath Examples; XPath Reference

According to your snippet you could select all tags TD that contain attribute data-odd.

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", "");
        }
}

Upvotes: 1

Related Questions