c# - 如何从 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);
}
帮助,请,我不知道如何做到这一点。祝你好运!
解决方案
我在评论中的建议似乎有效,请在此处查看工作版本: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);
}
}
}
推荐阅读
- c++ - 即使在使用警卫后也不能使用在另一个类中定义的结构
- amazon-web-services - auth0+passport.js 超过 1 个实例的重定向过多
- python - 从 Python 中的 DataFlow 读取 snappy 或 lzo 压缩文件
- c# - 如何通过客户端显示 WCF 服务的结果
- angular - 垫子导航中未显示儿童项目
- jenkins - jenkins job dsl - 没有方法签名:java.lang.String.call()
- condor - HTCondor:如何在平行宇宙中等到所有作业都完成?ParallelShutdownPolicy 不起作用
- excel - 如何编写 VBA/使用返回某个日期和单元格颜色内的单元格数量的命令链?
- powershell - 如何在 PowerShell 脚本中导入 CSV 文件?
- c++ - 如何修复我的 C++ 脚本中的运行时错误