1
votes

I am trying to scrape content inside a div:

<div itemprop="articleBody">random, unique content in this div, different each time</div>

My code to try and get the content between the div above

 var html = "random url eachtime.com";
 HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
 doc.LoadHtml(html);
 var nodes = doc.DocumentNode.SelectNodes("div[@itemprop=\"articleBody\"]");
 var inntertexts = nodes.Select(node => node.InnerText);
 articletext.Text = inntertexts.ToString();

When I visit the webpage to scrape the content between the div I get the following

exception...Value cannot be null. Parameter name: source

I have tried the xpath path like so too:

/html[1]/body[1]/div[3]/div[2]/div[3]/div[3]/div[5]/div[1]/div[1]/div[1]

I am trying to get articleBody from the following link: view-source:http://www.dailymail.co.uk/sciencetech/article-4408856/Samsung-building-flip-phone-TWO-screens.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490

How can I fix this so I can get the div's content?

1
check the value of itemprop, you have an uppercase B - Selman Genç
Yeah, I meant to add that to the div... Edditted - 4334738290

1 Answers

0
votes

It could be that div tag is inside other tags. If so, you could use "//div[@itemprop=\"articleBody\"]" (slashes at the front of div tag).

class Program
{
    static void Main(string[] args) => Task.Run(() => MainAsync(args)).Wait();

    static async Task MainAsync(string[] args)
    {
        var html = await GetResponseFromURI(new Uri("http://www.dailymail.co.uk/sciencetech/article-4408856/Samsung-building-flip-phone-TWO-screens.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490"));
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        var nodes = doc.DocumentNode.SelectNodes("//div[@itemprop=\"articleBody\"]");
        if (nodes != null)
        {
            Console.WriteLine(nodes.Select(node => node.InnerText).FirstOrDefault());
        }
        Console.ReadLine();
    }

    static async Task<string> GetResponseFromURI(Uri uri)
    {
        var response = "";
        using (var client = new HttpClient())
        {
            HttpResponseMessage result = await client.GetAsync(uri);
            if (result.IsSuccessStatusCode)
                response = await result.Content.ReadAsStringAsync();
        }
        return response;
    }
}

enter image description here

If there is not div tag with itemprop=\"articleBody\" at all, you will have to use null check.