【问题标题】:How to find a link in HTML under a certain header AND parse it如何在某个标题下的 HTML 中找到一个链接并解析它
【发布时间】:2017-04-11 01:09:34
【问题描述】:

我目前正在尝试根据其上方的标题解析来自 HTML 文档的链接,但无论我尝试什么,程序都无法找到它。 这是我的方法不起作用:

    public string findMajorURL(string collegeURL, string major)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(collegeURL);
        var root = doc.DocumentNode;
        var htmlNodes = root.Descendants();
        //Find html node containing the major heading
        foreach(HtmlNode node in htmlNodes)
        {
            if (node.InnerText == major)
            {
                HtmlNode target = node.NextSibling;
                List<string> links = target.Descendants("a").Select(a => a.Attributes["href"].Value).ToList();
                return links.First()+ "__IT WORKED__";
            }
        }
        return "Major not found";
    }

这就是我试图解析的 HTML:

    <div style="padding-left: 20px">
       <h3 id="ent1629">Biological Sciences </h3>
       <a href="preview_entity.php?catoid=5&ent_oid=1629&returnto=818">Go to information for this department.</a>
       <br>
       <p>...</p>
       <div id="data_c_1629" style="display: none">...</div>
       <!--script language="javascript">hideshow(data_c_1630)</script-->

用户输入的专业应该与标题生物科学相匹配。根据标题,我想获得 under 的链接,在本例中为 preview_entity.php?catoid=5&ent_oid=1629&returnto=818

警告:我不能将 XPath 与我拥有的 Visual Studio 版本一起使用,所以我假设以某种方式使用 LINQ 将是最好的方法,但我再次不确定。

编辑 事实证明,内部文本与专业不匹配,但是,我看不出这怎么可能,因为我直接从 html 代码中获取了它。有什么想法吗?

【问题讨论】:

    标签: c# html linq html-agility-pack


    【解决方案1】:

    根据发布的 HTML sn-p,node 在您的 if 块内引用 &lt;h3&gt; 元素,target 引用 &lt;h3&gt; 的下一个兄弟,即 &lt;a&gt;。也就是说,你不需要做target.Descendants("a")。直接从target 获取href 属性即可:

    if (node.InnerText == major)
    {
        HtmlNode target = node.NextSibling;
        return target.GetAttributeValue("href", "")+ "__IT WORKED__";
    }
    

    【讨论】:

    • 我试过这个,但显然它甚至没有输入 if 语句:/ 我不明白为什么内部文本不匹配,因为我什至直接从 html 文档中获取了内部文本,但仍然不匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2018-09-10
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2016-08-14
    相关资源
    最近更新 更多