【问题标题】:Getting Href property with anglesharp linq query使用anglesharp linq查询获取Href属性
【发布时间】:2016-05-08 21:56:46
【问题描述】:

我正在尝试了解如何使用anglesharp。

我根据示例 (https://github.com/AngleSharp/AngleSharp) 编写了这段代码:

        // Setup the configuration to support document loading
        var config = Configuration.Default.WithDefaultLoader();
        // Load the names of all The Big Bang Theory episodes from Wikipedia
        var address = "http://store.scramblestuff.com/";
        // Asynchronously get the document in a new context using the configuration
        var document = await BrowsingContext.New(config).OpenAsync(address);
        // This CSS selector gets the desired content
        var menuSelector = "#storeleft a";
        // Perform the query to get all cells with the content
        var menuItems = document.QuerySelectorAll(menuSelector);
        // We are only interested in the text - select it with LINQ
        var titles = menuItems.Select(m => m.TextContent).ToList();

        var output = string.Join("\n", titles);

        Console.WriteLine(output);

这按预期工作,但现在我想访问 Href 属性但我无法这样做:

var links = menuItems.Select(m => m.Href).ToList();

当我查看调试器时,我可以在结果视图中看到 HtmlAnchorElement 可枚举对象具有 Href 属性,但我显然没有尝试正确访问它。

文档中的示例都没有显示正在访问的属性,所以我猜它是如此简单,不需要显示,但我不知道该怎么做。

谁能告诉我应该如何访问具有锐角的 html 属性?

编辑:

当我将它转换为正确的类型时,这有效

foreach (IHtmlAnchorElement menuLink in menuItems)
        {
            Console.WriteLine(menuLink.Href.ToString());
        }

我将如何将它写成类似于titles 变量的Linq 语句?

【问题讨论】:

    标签: c# linq anglesharp


    【解决方案1】:

    我对这个话题有点晚了,但你可以使用

    string link = menuItem.GetAttribute("href");
    

    如果它是一个项目列表,则为这个

    List<string> menuItems = LinkList.Select(item => item.GetAttribute("href")) .ToList();
    

    【讨论】:

      【解决方案2】:

      替代har07's answer:

      var menuItems = document.QuerySelectorAll(menuSelector).OfType<IHtmlAnchorElement>();
      

      【讨论】:

        【解决方案3】:

        您可以按如下方式投射到IHtmlAnchorElement

        var links = menuItems.Select(m => ((IHtmlAnchorElement)m).Href).ToList();
        

        或使用Cast&lt;IHtmlAnchorElement&gt;()

        var links = menuItems.Cast<IHtmlAnchorElement>()
                             .Select(m => m.Href)
                             .ToList();
        

        【讨论】:

          猜你喜欢
          • 2018-11-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多