无法使用HtmlAgilityPack在C#中解析html表

时间:2017-11-20 12:44:15

标签: c# html-agility-pack

我想阅读this link中显示的表格。

当我尝试使用HtmlAgilityPack时,我收到null

var nodes = document.DocumentNode.SelectNodes("//table[contains(@class, 'table')]");
你能告诉我这是什么问题吗?我是以错误的方式做的吗?

2 个答案:

答案 0 :(得分:1)

你的xpath没有任何问题。我只是假设你不知道如何从表中获取数据。你需要查找xpath。

    public static void Main(string[] args)
    {
        HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.manualslib.com/brand/A.html");
            request.Method = "GET";
            request.ContentType = "text/html;charset=utf-8";

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    doc.Load(stream, Encoding.GetEncoding("utf-8"));
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
        }
        //Works fine
        HtmlNode tablebody = doc.DocumentNode.SelectSingleNode("//table[contains(@class, 'table')]/tbody");
        foreach(HtmlNode tr in tablebody.SelectNodes("./tr"))
        {
            Console.WriteLine("\nTableRow: ");
            foreach(HtmlNode td in tr.SelectNodes("./td"))
            {
                if (td.GetAttributeValue("class", "null") == "col1")
                {
                    Console.Write("\t " + td.InnerText);
                }
                else
                {
                    HtmlNode temp = td.SelectSingleNode(".//div[@class='catel']/a");
                    if (temp != null)
                    {
                        Console.Write("\t " + temp.GetAttributeValue("href", "no url"));
                    }
                }


            }
        }
        Console.ReadKey();
    }

首先我们使用xpath进入节点tbody,但前提是表中类中的属性包含' table':

//table[contains(@class, 'table')]/tbody

现在我们选择所有名为tr(表格行)的节点:

./ TR

这里的点意味着从当前的上下文开始我们将找到所有的tr节点。然后在每个tr节点中,我们将找到所有td节点:

./ TD

现在,我们希望在每个表格单元格中获取数据。在第一个td中,我们知道class-attribute等于' col1'。因此,如果td包含具有该值的类 - 那么我们希望在该td节点内获取文本。

如果它不包含该属性,我们知道我们希望div内的anchor-tag具有类属性值为' catel'。

在锚标记内,我们想要获得href属性的值。

答案 1 :(得分:0)

使用这种方式:

document.DocumentNode.SelectNodes("//div[@class='col-sm-8']/table[contains(@class, 'table')]/tbody/tr")