HtmlAgilityPack : illegal characters in path

c# html-agility-pack html-parsing

Question

I'm getting an "illegal characters in path" error in this code. I've mentioned "Error Occuring Here" as a comment in the line where the error is occuring.

var document = htmlWeb.Load(searchUrl);
var hotels = document.DocumentNode.Descendants("div")
             .Where(x => x.Attributes.Contains("class") &&
             x.Attributes["class"].Value.Contains("listing-content"));

int count = 1;
foreach (var hotel in hotels)
{
    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.OptionFixNestedTags = true;
    htmlDoc.Load(hotel.InnerText);      // Error Occuring Here //
    if (htmlDoc.DocumentNode != null)
    {
        var hotelName = htmlDoc.DocumentNode.SelectNodes("//div[@class='business-container-inner']//div[@class='business-content clearfix']//div[@class='business-name-wrapper']//h3[@class='business-name fn org']//div[@class='srp-business-name']//a[0]");
        foreach (var name in hotelName)
        {
            Console.WriteLine(name.InnerHtml);
        }
    }
}

Accepted Answer

You should use LoadHtml method with loads a string. Load method loads from file

htmlDoc.LoadHtml(hotel.InnerText);   

Popular Answer

This simply means you're trying to load a file with an invalid character in the file path/name.

The error is here:

htmlDoc.Load(hotel.InnerText); 

..because that overload expects the path to the file:

public void Load(string path)

Use LoadHtml to load a HTML fragment:

public void LoadHtml(string html)



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why