Html Agility Pack - Select Divs inside Div



对于HTML Agility Pack来说是全新的。我一直在寻找和尝试许多例子,但还没有得出结论。一定是做错了什么…希望你能帮助我。

我的目标是解析来自网站的最新消息,包括图像,标题和日期-非常简单。我设法从div中获得图像(背景属性),但div是嵌套的,出于某种原因,我无法访问它们的值。这是我的代码

using System;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{
var html = @"https://pristontale.eu/";
HtmlWeb web = new HtmlWeb();
var doc = web.Load(html);

var news = doc.DocumentNode.SelectNodes("//div[contains(@class,'index-article-wrapper')]");

foreach (var item in news){
var image = Regex.Match(item.GetAttributeValue("style", ""), @"(?<=url()(.*)(?=))").Groups[1].Value;
var title = item.SelectSingleNode("//div[@class='article-title']").InnerText;
var date = item.SelectSingleNode("//div[@class='article-date']").InnerText;
Console.WriteLine(image, title, date);

}
}
}

这就是HTML的样子

<div class="index-article-wrapper" onclick="location.href='article.php?id=2';" style="background-image: url(https://cdn.discordapp.com/attachments/765749063621935104/884439050562461696/1_1.png)">
<div class="meta-wrapper">
div class="article-date">5 Sep, 2021</div>
<div class="article-title">Server merge v1.264 update</div>
</div>
</div>

目前它正确地抓住了我所有的4篇新闻文章,但只有图像-我如何得到每个标题和日期?这里有一个小提琴https://dotnetfiddle.net/BVcAmH

感谢您的帮助

我刚刚意识到代码一直都是正确的,唯一的缺陷是Console.WriteLine

错了

Console.WriteLine(image, title, date);

正确

Console.WriteLine(image + " " + " " + title + " " + date);

最新更新