代码改变世界

AngleSharp 实战(04)之遍历内部超链接(a)元素的 Href 和 InnerText

  音乐让我说  阅读(355)  评论(0编辑  收藏  举报

文档地址: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.TryTrim();
                string href = null;
                if (postTitleElemItem.HasAttribute("href"))
                {
                    href = postTitleElemItem.GetAttribute("href").TryTrim();
                }
                Console.WriteLine("{0}. {1} ( {2} )", i, title, href);
            }
            
            Console.WriteLine("{0}", Environment.NewLine);
        }
    }
}
复制代码

 

 

谢谢浏览!

点击右上角即可分享
微信分享提示