HtmlAgilityPack - 如何理解页面重定向和加载重定向页面

时间:2011-10-15 23:18:55

标签: c# redirect html-agility-pack

使用HtmlAgilityPack和c#4.0如何确定页面是否被重定向。我正在使用此方法加载页面。

HtmlDocument hdMyDoc = hwWeb.Load(srPageUrl);

我想是示例重定向结果

返回内部html

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

c#4.0

2 个答案:

答案 0 :(得分:3)

对于这种情况,解析HTML是最好的方法。

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");
}

答案 1 :(得分:3)

假设文档格式相对较好,我想你可以这样做:

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();
}
相关问题