首页 > 解决方案 > 如何从 HTML 中获取所有标题元素?HTMLAgilityPack,C#

问题描述

处理解析器音乐网站。需要在播放列表中获取有关歌曲的更多信息。在使用 AngleSharp 失败后,我使用 HTMLAgilityPack。因此,找到歌曲的标题,例如:

        <div class="datagrid-cell cell-artist">
<div class="ellipsis"><a class="datagrid-label datagrid-label-main" itemprop="byArtist" title="Drake" href="/ru/artist/246791">Drake</a></div></div>

但是使用我的代码,我无法获得所需的属性。代码(在此处使用输入链接描述):

 class Program
{
    static async Task Main(string[] args)
    {

        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        var client = new HttpClient();
        string html = await client.GetStringAsync("https://www.deezer.com/ru/playlist/2872124702");
        document.LoadHtml(html);
        if (document.DocumentNode != null)
        {

            foreach (HtmlNode node in document.DocumentNode.Descendants("div").Where(d =>
            d.Attributes.Contains("class") && d.Attributes["title"].Value.Contains("ellipsis")))
            {
                string title = node.SelectSingleNode(".//a").Attributes["title"].Value; //I think - need InnerText
                Console.WriteLine(title);
            }

帮助,请,我不知道如何做到这一点。祝你好运!

标签: c#htmlhtml-agility-pack

解决方案


我在评论中的建议似乎有效,请在此处查看工作版本:https ://dotnetfiddle.net/h8OrbG

    using System;

public class Program
{
    public static void Main()
    {
        var doc = new HtmlAgilityPack.HtmlDocument();
        var html = "<div class='datagrid-cell cell-artist'><div class='ellipsis'><a class='datagrid-label datagrid-label-main' itemprop='byArtist' title='Drake' href='/ru/artist/246791'>Drake</a></div></div>";
        doc.DocumentNode.AppendChild(HtmlAgilityPack.HtmlNode.CreateNode(html));
        foreach (var node in doc.DocumentNode.SelectNodes("//a[@itemprop='byArtist']"))
        {
            Console.WriteLine(node.Attributes["title"].Value);
        }
    }
}

推荐阅读