使用HTML Agility Pack選擇下一個元素

c# html html-agility-pack

我正在使用HTML Agility Pack並在class="fileHeader"中搜索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
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow