3

我试图了解如何使用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());
        }

我将如何将其写为像标题变量一样的 Linq 语句?

4

3 回答 3

6

替代har07 的答案

var menuItems = document.QuerySelectorAll(menuSelector).OfType<IHtmlAnchorElement>();
于 2016-05-09T01:04:25.993 回答
3

您可以IHtmlAnchorElement按以下方式转换:

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

或使用Cast<IHtmlAnchorElement>()

var links = menuItems.Cast<IHtmlAnchorElement>()
                     .Select(m => m.Href)
                     .ToList();
于 2016-05-09T00:06:47.927 回答
2

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

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

或者如果它是一个项目列表

List<string> menuItems = LinkList.Select(item => item.GetAttribute("href")) .ToList();
于 2020-08-01T17:11:16.030 回答