HtmlAgilityPack - How to understand page redirected and load redirected page

c# html-agility-pack redirect

Question

With using HtmlAgilityPack and c# 4.0 how can you determine whether page is being redirected or not. I am using this method to load page.

HtmlDocument hdMyDoc = hwWeb.Load(srPageUrl);

And example redirection result i suppose

Returned inner html

<meta http-equıv="refresh" content="0;URL=http://www.pratikev.com/fractalv33/pratikEv/pages/home.jsp">

c# 4.0

Accepted Answer

For this case, parse the HTML is the best way.

var page = "...";
var doc = new HtmlDocument();
doc.Load(page);
var root = doc.DocumentNode;
var select = root.SelectNodes("//meta[contains(@content, 'URL')]");
try
{
    Console.WriteLine("has redirect..");
    Console.WriteLine(select[0].Attributes["content"].Value.Split('=')[1]);
}
catch
{
    Console.WriteLine("have not redirect using HTML");
}

Popular Answer

Assuming the document is relatively well-formed, I suppose you could do something like this:

static string GetMetaRefreshUrl(string sourceUrl)
{
    var web = new HtmlWeb();
    var doc = web.Load(sourceUrl);
    var xpath = "//meta[@http-equiv='refresh' and contains(@content, 'URL')]";
    var refresh = doc.DocumentNode.SelectSingleNode(xpath);
    if (refresh == null)
        return null;
    var content = refresh.Attributes["content"].Value;
    return Regex.Match(content, @"\s*URL\s*=\s*([^ ;]+)").Groups[1].Value.Trim();
}


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