HtmlAgilityPack:如何检查元素是否可见?

mus*_*fan 2 c# html-agility-pack

我正在做一些HTML解析,我正在使用HtmlAgilityPack,我试图检查如果html是在浏览器中呈现的话节点元素是否可见.

通过可见,我可能满足于检查display和visibility样式值.(除非有额外的东西我应该担心吗?).

那么,我该怎么做呢?有简单的构建方式吗?我可以使用一些XPath魔法吗?(目前我对XPath的了解不多).

我曾考虑手动解析样式值,但宁愿将其作为最后的手段保存.或者这是我唯一的选择吗?

仅供参考,我正在使用的对象是这样的:

HtmlAgilityPack.HtmlNode node = GetNode();
Run Code Online (Sandbox Code Playgroud)

mus*_*fan 5

好的,所以我设法做到了这一点,至少是为了我的需要.但请注意,正如其他评论所述,这不允许您检查最终用户是否可以看到(在屏幕上)元素.

我采用的方法简单检查了一些基本规则:如果元素的style属性包含display:noneor visibility:hidden,则元素"不可见" ,或者祖先元素具有相同的样式规则.

考虑到这一点,这是我的代码,为我做的工作:

private static bool IsNodeVisible(HtmlAgilityPack.HtmlNode node)
{
    var attribute = node.Attributes["style"];

    bool thisVisible = false;

    if (attribute == null || CheckStyleVisibility(attribute.Value))
        thisVisible = true;

    if (thisVisible && node.ParentNode != null)
        return IsNodeVisible(node.ParentNode);

    return thisVisible;
}

private static bool CheckStyleVisibility(string style)
{
    if (string.IsNullOrWhiteSpace(style))
        return true;

    var keys = ParseHtmlStyleString(style);

    if (keys.Keys.Contains("display"))
    {
        string display = keys["display"];
        if (display != null && display == "none")
            return false;
    }

    if (keys.Keys.Contains("visibility"))
    {
        string visibility = keys["visibility"];
        if (visibility != null && visibility == "hidden")
            return false;
    }

    return true;
}

public static Dictionary<string, string> ParseHtmlStyleString(string style)
{
    Dictionary<string, string> result = new Dictionary<string, string>();

    style = style.Replace(" ", "").ToLowerInvariant();

    string[] settings = style.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string s in settings)
    {
        if (!s.Contains(':'))
            continue;
        string[] data = s.Split(':');
        result.Add(data[0], data[1]);
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

这个的入口点是IsNodeVisible并将检查HtmlNode传递给它的可见性.