使用C#+XPath+HtmlAgilityPack輕松搞一個資源下載器


HtmlAgilityPack簡介

HtmlAgilityPack是一個開源的解析HTML元素的類庫,最大的特點是可以通過XPath來解析HMTL,如果您以前用C#操作過XML,那么使用起HtmlAgilityPack也會得心應手。目前版本更新的是非常的快,最新更新時間還是19年的呢!

 XPath介紹

XPath即為XML路徑語言,它是一種用來確定XML(標准通用標記語言的子集)文檔中某部分位置的語言。XPath基於XML的樹狀結構,提供在數據結構樹中找尋節點的能力。起初 XPath 的提出的初衷是將其作為一個通用的、介於XPointer與XSL間的語法模型。但是 XPath 很快的被開發者采用來當作小型查詢語言。

具體代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.IO;
using System.Net;

namespace DataGridViewDemo
{
    public class HttpHelper
    {
        static readonly string urlTemplate = "http://yun.java1234.com/search?page={0}&q={1}";
        public static List<BDWPResource> Request(string key, string start)
        {
            string url = string.Format(urlTemplate, key, start);
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
            try
            {
                HtmlWeb webClient = new HtmlWeb();
                HtmlDocument doc = webClient.Load(url);
                if (doc != null)
                {
                    //加載文檔對象
                    {
                        var content = doc.DocumentNode.SelectSingleNode("/html/body/div[2]/div[3]/div/div/div[2]/ul");
                        if (content != null)
                        {
                            List<BDWPResource> list = new List<BDWPResource>();
                            var targetLi = content.SelectNodes(@"li");
                            foreach (var item in targetLi)
                            {
                                list.Add(new BDWPResource()
                                {
                                    title = item.SelectSingleNode("span[1]/a").InnerText,
                                    unescapedUrl = "http://yun.java1234.com/" + item.SelectSingleNode("span[1]/a").Attributes["href"].Value.Trim(),
                                    content = item.SelectSingleNode("span[2]").InnerText.Trim()
                                });
                            }
                            return list;
                        }
                    }
                    return null;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}

效果圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM