使用 HTMLAgilityPack 从节点的子节点中选择所有

2024-05-14

我有以下代码用于获取 html 页面。将网址设置为绝对,然后将链接设置为 rel nofollow 并在新窗口/选项卡中打开。我的问题是关于将属性添加到<a>s.

        string url = "http://www.mysite.com/";
        string strResult = "";            

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if ((request.HaveResponse) && (response.StatusCode == HttpStatusCode.OK)) {
            using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
                strResult = sr.ReadToEnd();
                sr.Close();
            }
        }

        HtmlDocument ContentHTML = new HtmlDocument();
        ContentHTML.LoadHtml(strResult);
        HtmlNode ContentNode = ContentHTML.GetElementbyId("content");

        foreach (HtmlNode node in ContentNode.SelectNodes("/a")) {
            node.Attributes.Append("rel", "nofollow");
            node.Attributes.Append("target", "_blank");
        }

        return ContentNode.WriteTo();

谁能看到我做错了什么吗?在这里尝试了一段时间但没有运气。此代码表明 ContentNode.SelectNodes("/a") 未设置为对象的实例。我想尝试将蒸汽设置为0?

干杯, 丹尼斯


Is ContentNode无效的?您可能需要在查询中选择 select-single"//*[@id='content']".

有关信息,"/a"表示所有锚点在根. does "descendant::a"工作?还有HtmlElement.GetElementsByTagName这可能更容易 - 即yourElement.GetElementsByTagName("a").

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 HTMLAgilityPack 从节点的子节点中选择所有

的相关文章

随机推荐