WebDriver can use xpath to locate elements, but Html Agility Pack can't.

c# html-agility-pack visual-studio-2010 webdriver xpath


My XPath queries have never worked with HTML Agility Pack; they only ever function with the simplest of queries:




However, Html Agility Pack is unable to manage them if they get more complex. The following example shows the issue: I browse to Google using WebDriver and return the page source, which is then sent to HTML Agility Pack, and both WebDriver and HTML Agility Pack make an effort to find the element/node (C#):

//The XPath query
const string xpath = "//form//tr[1]/td[1]//input[@name='q']";

//Navigate to Google and get page source
var driver = new FirefoxDriver(new FirefoxProfile()) { Url = "http://www.google.com" };

//Can WebDriver find it?
var e = driver.FindElementByXPath(xpath);
Console.WriteLine(e!=null ? "Webdriver success" : "Webdriver failure");

//Can Html Agility Pack find it?
var source = driver.PageSource;
var htmlDoc = new HtmlDocument { OptionFixNestedTags = true };
var nodes = htmlDoc.DocumentNode.SelectNodes(xpath);
Console.WriteLine(nodes!=null ? "Html Agility Pack success" : "Html Agility Pack failure");


In this instance, WebDriver was able to discover the object whereas HTML Agility Pack was unable to.

I'm aware that changing the xpath in this instance to //input[@name='q'] will solve the problem, but that will only solve the problem in this particular example, which isn't the point. Instead, I need something that will behave in a manner similar to that of WebDriver's xpath engine, or even that of the FirePath or FireFinder add-ons for Firefox.

Why can't Html Agility Pack locate it too if WebDriver can?

5/25/2011 4:30:43 PM

Accepted Answer

You are having trouble with the FORM element. By default, HTML Agility Pack the piece is handled differently never reports having children.

In the specific instance you provided, this search does indeed locate the desired element:


This, however, does not, making it obvious that the form element is confusing the parser:


However, that behavior may be altered. The form will provide you with child nodes if you add this line before processing the HTML:

5/25/2011 6:20:06 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow