文档地址:https://anglesharp.github.io/docs/Examples.html
直接贴代码了:
using System; using System.Linq; using System.Threading.Tasks; using AngleSharp; using AngleSharp.Dom; using AngleSharp.Html.Parser; namespace AngleSharpSamples { class Program { static async Task Main(string[] args) { var config = Configuration.Default.WithDefaultLoader(); var address = "https://www.cnblogs.com"; var context = BrowsingContext.New(config); var document = await context.OpenAsync(address); var cellSelector = "div.post_item"; IHtmlCollection<IElement> cells = document.QuerySelectorAll(cellSelector); int i = 0; foreach (IElement postElemItem in cells) { IElement postTitleElemItem = postElemItem.QuerySelector("a.titlelnk"); //如果元素不存在,则 postTitleElemItem = null if (postTitleElemItem == null) { continue; } i++; string title = postTitleElemItem.TextContent; Console.WriteLine("{0}. {1}", i, title); } Console.WriteLine("{0}", Environment.NewLine); } } }
谢谢浏览!