0

我正在使用 HTML Agility Pack 并在子 h4 元素中div使用class="fileHeader"它进行搜索。"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;
                    }
                }
            }
        }
    }
}
4

1 回答 1

0

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
}
于 2013-09-05T17:59:48.847 回答