Search code examples
c#htmlhtml-agility-packselectsinglenode

htmlagilitypack selectsinglenode returning null


The problem about that is, it runs correctly just once in a 20 try or so and it is totally random. Couldnt handle the situation... help will be appreciated ^^

        WebClient client = new WebClient();

        client.Encoding = Encoding.UTF8;
        try
        {
            html = client.DownloadString(url);
        }
        catch (WebException)
        {
            if (MessageBox.Show("url'de hata", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
            {

            }

        }

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        HtmlWeb web = new HtmlWeb();

        doc.LoadHtml(html);

        HtmlNode foo = doc.DocumentNode.SelectSingleNode(Xpath);    

        Listbox1.Items.Add(foo.Attributes["href"].Value); //error here 
        currentPage = (foo.Attributes["href"].Value);

Solution

  • You have to check for nodes is not null. Server may return different response for every request. Server might be returning 20 to 1 element you want. Are you sure the contents are the same? The session may vary depending on the situation. Make sure that successful and unsuccessful contents are equal.