XPath gives different results in browser and HtmlAgilityPack

I am trying to parse a section of a webpage using HtmlAgilityPack in a C # program. The following is a simplified version of this section of the page (edited 1/30/2015 2:40 PM EST):

<html>
    <body>
        <div id="main-box">
            <div>
                <div>...</div>
                <div>

                    <div class="other-classes row-box">
                        <div>...</div>
                        <div>...</div>
                        <div>
                            <p>
                                <a href="/some/other/path">
                                    <img src="/path/to/img" />
                                </a>
                            </p>
                            <p>
                                ...
                                <a href="/test/path?a=123">Correct</a> extra text
                            </p>
                        </div>
                        <div>
                            ...
                            <p>
                                <ul>
                                    ...
                                    <li>
                                        <span>
                                            <a href="/test/path?a=456&b=123">Never Selected</a>
                                            and <a href="/test/path?a=789">Never Selected</a>.
                                        </span>
                                    </li>
                                </ul>
                            </p>
                        </div>
                        ...
                    </div>

                    <div class="other-classes row-box">
                        <div>...</div>
                        <div>...</div>
                        <div>
                            <p>
                                No "a" tag this time
                            </p>
                        </div>
                        <div>
                            <p>
                                <ul>
                                    <li>
                                        <span>
                                            <span style="display:none;">
                                                <a href="/some/other/path">Never Selected</a>
                                            </span>
                                        </span>
                                    </li>
                                    <li>
                                        <span>
                                            <a href="/test/path?a=abc&b=123">Correct</a>
                                            and <a href="/test/path?a=def">Wrongly Selected</a>.
                                        </span>
                                    </li>
                                </ul>
                            </p>
                        </div>
                        ...
                    </div>

                    <div class="other-classes row-box">
                        <div>...</div>
                        <div>...</div>
                        <div>
                            <p>
                                <span>
                                    <a href="/test/path?a=ghi">Correct</a>
                                </span>
                            </p>
                            <p>
                                ...
                                <a href="/test/path?a=jkl">Wrongly Selected</a> extra text
                            </p>
                        </div>
                        <div>
                            <p>
                                <ul>
                                    ...
                                    <li>
                                        <span>
                                            <a href="/test/path?a=mno&b=123">Never Selected</a>
                                            and <a href="/test/path?a=pqr">Never Selected</a>.
                                        </span>
                                    </li>
                                </ul>
                            </p>
                        </div>
                        ...
                    </div>

                </div>
            </div>
        </div>
    </body>
</html>

I am trying to get the first and only first tag “a” with the GET parameter “a” in the third or fourth child div of each div with the class “row-box” (those that have the word “Correct” in them in the above example). I came up with the following XPath, which receives these nodes and only these nodes both in the Chrome inspector and in addition to Firepath for Firefox (wrapped for readability):

//div[@id="main-box"]/div/div[2]/div[contains(@class, "row-box")]/div[
  (position() = 3 or position() = 4) and descendant::a[
    contains(@href, "a=")
  ]
][1]/descendant::a[contains(@href, "a=")][1]

, HttpWebRequest, HtmlDocument SelectNodes (xpath) DocumentNode XPath, , " " . , , XPath , "[1]", ( ):

//div[@id="main-box"]/div/div[2]/div[contains(@class, "row-box")]/div[
  (position() = 3 or position() = 4) and descendant::a[
    contains(@href, "a=")
  ]
][1]/descendant::a[contains(@href, "a=")]

, HtmlAgilityPack, XPath, , - , , . HTML, , , , - , HtmlAgilityPack - .

- , , XPath, , , HtmlAgilityPack, .

, #, , , .

using System;
using System.Net;
using HtmlAgilityPack;

...

static void Main(string[] args)
{
    string url = "http://www.deerso.com/test.html";
    string xpath = "//div[@id=\"main-box\"]/div/div[2]/div[contains(@class, \"row-box\")]/div[(position() = 3 or position() = 4) and descendant::a[contains(@href, \"a=\")]][1]/descendant::a[contains(@href, \"a=\")][1]";
    int statusCode;
    string htmlText;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

    request.Accept = "text/html,*/*";
    request.Proxy = new WebProxy();
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";

    using (var response = (WebResponse)request.GetResponse())
    {
        statusCode = (int)((HttpWebResponse)response).StatusCode;
        using (var stream = response.GetResponseStream())
        {
            if (stream != null)
            {
                using (var reader = new System.IO.StreamReader(stream))
                {
                    htmlText = reader.ReadToEnd();
                }
            }
            else
            {
                Console.WriteLine("Request to '{0}' failed, response stream was null", url);
                htmlText = null;
                return;
            }
        }
    }

    HtmlNode.ElementsFlags.Remove("form"); //fix for forms
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(htmlText);

    HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(xpath);

    foreach (HtmlNode node in nodes)
    {
        Console.WriteLine("Node Found:");
        Console.WriteLine("Text: {0}", node.InnerText);
        Console.WriteLine("Href: {0}", node.Attributes["href"].Value);
        Console.WriteLine();
    }

    Console.WriteLine("Done!");
}
+4
2

Html

//a[contains(@href,'a=')][1], <a> .

, - , ..

(//a[contains(@href,'a=')])[1]

, , node , xpath :

//div[contains(@class,'row-box')](//a[contains(@href,'a=')])[1]

, :

  • div, .

# :

// Get the <div> elements we know are ancestors to the <a> elements we want
HtmlNodeCollection topDivs = doc.DocumentNode.SelectNodes("//a[contains(@href,'?a=')]/ancestor::div[contains(@class,'row-box')]");

// Create a new list to hold the <a> elements
List<HtmlNode> linksWeWant = new List<HtmlNode>(topDivs.Count)

// Iterate through the <div> elements and get the first descendant
foreach(var div in topDivs)
{
    linksWeWant.Add(div.SelectSingleNode("(//a[contains(@href,'?a=')])[1]"));
}

, xpath:

HtmlAgilityPack, :

<a href = "/test/path?a=123">
<a href = "/test/path?a=abc&b=123">
<a href = "/test/path?a=ghi">

:

//div[contains(@class,'row-box')]        -> Get nodeset of <div class="*row-box*"> elements
/descendant::a                           -> From here get all descendant <a> elements
[contains(@href,'a=') and position()=1]  -> Filter according to href value and element being the first descendant

, xpath - /descendant::a[contains(@href,'a=') and position()=1] vs /descendant::a[contains(@href,'a=')][1]. [1] , .

+1

"a" GET "a" div div "row-box"

, XPath. XQuery:

for $rowBox in //div[contains(@class, 'row-box')]
    let $firstRelevant := ($rowBox/div[
            (position() = 3 or position() = 4)
            and .//a[contains(@href, 'a=')]
        ])[1]
    return ($firstRelevant//a[contains(@href, 'a=')])[1]

(.. (...)[...]), , XPath.

# , XQuery:

  • //div[contains(@class, 'row-box')]:
    • ./div[(position() = 3 or position() = 4) and .//a[contains(@href, 'a=')]
    • :
      • .//a[contains(@href, 'a=')]
0

All Articles