首页 > 解决方案 > 如何将 HtmlAttribute 转换为字符串?

问题描述

var web = new HtmlWeb();
var doc = web.Load(page);

var Articles = doc.DocumentNode.SelectNodes("//*[@class = 'b-product-grid-tile js-tile-container']"); 
var href = doc.DocumentNode.SelectNodes("//a[@href]");

foreach (HtmlNode link in href)
            {
                HtmlAttribute att = link.Attributes["href"];
                _entries.Add(new EntryModel { Link = att });

                // att.ToString(); <----- Want to convert the HtmlAttribute to a string.
            }

我的 Scraper 的完整代码:

我的 Scraper 的完整代码

入口型号列表:

入口模型列表

主窗口:

主窗口

我需要的链接:

我需要的链接

标签: c#htmlweb-scrapinghreftostring

解决方案


最简单的方法是使用System.Web.Mvc.TagBuilder该类:

var attributes = new { @class = "myClass", id = "elId" };

var tag = new TagBuilder("href");
tag.MergeAttributes(new RouteValueDictionary(attributes));

return tag.ToString();

推荐阅读