繁体   English   中英

使用HTML Agility Pack选择下一个元素

[英]Selecting the next element using HTML Agility Pack

我正在使用HTML Agility Pack,并使用class="fileHeader"搜索div ,该div在子h4元素中具有"RelayClinical Patient Education with Animations Install zip" 找到后,我想捕获该特定块的定位标记内的"href"属性。 我怎么才能得到它?

HTML来源

<div class="fileHeader" id="fileHeader_7311111">
    <h4 class="collapsed">RelayClinical Patient Education with Animations Install zip</h4>
    <div class="defaultMethod">
        <a class="buttonGrey" href="https://mckc-esd.subscribenet.com/cgi-bin/download?rid=2511740931&amp;rp=DTM20130905162949MzcyODIwNjM0" title="Clicking this link will open a new window." rel="noreferrer">
            HTTPS Download
        </a>
    </div>
</div>

HtmlNodeCollection fileHeaderNodes = bodyNode.SelectNodes("//div[@class='fileHeader']//h4");
foreach (HtmlNode fileHeader in fileHeaderNodes)
{
    if (fileHeader.InnerText.Trim() == "RelayClinical Patient Education with Animations Install zip")
    {
        HtmlNodeCollection fileHeaderNodes = bodyNode.SelectNodes("//div[@class='fileHeader']//h4");
        foreach (HtmlNode fileHeader in fileHeaderNodes)
        {
            if (fileHeader.InnerText.Trim() == "RelayClinical Patient Education with Animations Install zip")
            {
                foreach (HtmlNode link in fileHeader.SelectNodes("//a[@href]"))
                {
                    // extract the link and put in dataUrl var
                    if ((link.InnerText.Trim() == "HTTPS Download") && isFound == true)
                    {
                        count++;
                        // select all a tags (html anchor tags) that have a href attribute
                        HtmlAttribute att = link.Attributes["href"];
                        dataUrl = att.Value;
                    }
                }
            }
        }
    }
}

与其选择h4元素,不如直接选择a元素。 然后,您可以获取href属性。

var h4Text = "RelayClinical Patient Education with Animations Install zip";
var xpath = String.Format(
    "//div[@class='fileHeader' and h4='{0}']/div[@class='defaultMethod']/a",
    h4Text
);
var anchor = doc.DocumentNode.SelectSingleNode(xpath);
if (anchor != null)
{
    var attr = anchor.GetAttributeValue("href", null);
    // do stuff with attr
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM