C# 爬虫(学习笔记)

扩展

在前端网页上使用JS、Jquery能很好得操作Dom元素,在后台请求到网页数据得时候,建议使用HtmlAgilityPack开源扩展类,能够高效的解析我们抓取到的html数据。

优势

在.NET技术下,解析html工具也很多,比如很多人可能会使用htmlparser,或者微软的MSHTML,htmlparser虽然比较易上手,但是相对应的解析速度较慢,而HtmlAgilityPack解析速度相当快,并且开源,易用,它可以帮助我们解析html文档就像用XmlDocument类来解析xml一样轻松、方便。

传送门

HtmlAgilityPac简单使用

A.网页源码

<!DOCTYPE html>
<html>
<head>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge,chrome=1" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="renderer" content="webkit">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
    <title>蓝格赛商城</title>
</head>

<body id="body">
    <header class="ns-header" style="border-bottom: 3px solid #1F93D3;">
        <div class="top-bar ns-border-color-gray">
            <div class="w1200 clearfix">
                <div class="pull-left">您好,欢迎光临蓝格赛商城!</div>
                <div class="pull-right">
                    <a href="https://www.rexelmall.com.cn/login/index.html" class="ns-text-color" style="margin-right: 5px;">登录</a>
                    <span style="margin-right: 5px;">|</span>
                    <a href="https://www.rexelmall.com.cn/login/register.html">注册</a>
                </div>
            </div>
        </div>
        <div class="w1200 middle" id="top_search" style="background: white;">
            <a class="ns-logo" href="https://www.rexelmall.com.cn">
                <img class="self-adaption-img" src="https://img3.rexelmall.com.cn/upload/config/2019071809374252959.png" />
            </a>
            <div class="ns-search">
                <div class="clearfix" style="margin-top: 7px;">
                    <input class="ns-border-color ns-text-color-black" type="text" id="keyword" value=""
                           placeholder="请输入您要搜索的产品名称, 品牌或型号" data-search-words="">
                    <button class="btn btn-primary" type="button">搜索</button>
                </div>
                <div id="tjlist">
                    <a href="https://www.rexelmall.com.cn/list.html?brand_name=SND" style="margin-right:10px">施耐德</a>
                    <a href="https://www.rexelmall.com.cn/list.html?brand_name=SIE" style="margin-right:10px">西门子</a>
                    <a href="https://www.rexelmall.com.cn/list.html?brand_name=WEI" style="margin-right:10px">魏德米勒</a>
                    <a href="https://www.rexelmall.com.cn/list.html?category_id=1126" style="margin-right:10px">断路器</a>
                    <a href="https://www.rexelmall.com.cn/list.html?category_id=74" style="margin-right:10px">接触器</a>
                    <a href="https://www.rexelmall.com.cn/list.html?category_id=75" style="margin-right:10px">继电器</a>
                    <a href="https://www.rexelmall.com.cn/list.html?category_id=58" style="margin-right:10px">电源</a>
                    <a href="https://www.rexelmall.com.cn/list.html?category_id=1135"
                       style="margin-right:10px">?业连接器</a>
                </div>
            </div>
            <div class="page_erweima" id="erweima">
                <img src="https://img3.rexelmall.com.cn/upload/config/2020031902460348516.jpg">
            </div>
            <div class="ns-cart ns-border-color-gray">
                <div class="cart common-text-color">
                    <i class="icon icon-shopping-cart"></i>
                    <span>我的购物车</span>
                    <em class="shopping-amount common-bg-color">0</em>
                </div>
                <div class="list ns-border-color-gray"></div>
            </div>
        </div>
        <nav class="w1200 clearfix">
            <ul class="menu">
                <li>
                    <a class="ns-border-color-hover ns-text-color-hover" href="https://www.rexelmall.com.cn/brands.html"
                       title="品牌中心">品牌中心</a>
                    <div class="ns-text-color">1</div>
                </li>
                <li>
                    <a class="ns-border-color-hover ns-text-color-hover" target="_blank" href="/index/station" title="MRO驻场方案">MRO驻场方案</a>
                    <div class="ns-text-color">2</div>
                </li>
                <li>
                    <a class="ns-border-color-hover ns-text-color-hover" href="https://www.rexelmall.com.cn/article/detail?article_id=19&amp;class_id=7" title="专业照明服务">专业照明服务</a>
                    <div class="ns-text-color">3</div>
                </li>
            </ul>
        </nav>
    </header>
</body>
</html>

B.操作DOM元素

  • 1.通过class、id选择器获取节点
//1.通过class、id选择器获取节点
HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(filePath);
HtmlNode classNodes = doc.DocumentNode.SelectSingleNode("//div[@class='ns-search']");
Console.WriteLine("class选择器----------------------------------------------------------------------------");
Console.WriteLine(classNodes.InnerHtml);
HtmlNode idNodes = doc.DocumentNode.SelectSingleNode("//div[@id='erweima']");
Console.WriteLine("id选择器-------------------------------------------------------------------------------");
Console.WriteLine(idNodes.InnerHtml);
  • 2.通过索引定位获取节点
//2.通过索引定位获取节点
HtmlNode IndexesNodes = doc.DocumentNode.SelectSingleNode("//body[1]/header[1]/div[2]/div[1]");
Console.WriteLine("索引定位-------------------------------------------------------------------------------");
Console.WriteLine(IndexesNodes.InnerHtml);
  • 3.一次行获取ul下面的所有li标签节点
//3.一次行获取ul下面的所有li标签节点
HtmlNodeCollection liNodes = doc.DocumentNode.SelectNodes("//ul[@class='menu']/li");
Console.WriteLine("li标签------------------------------------------------------------------------");
foreach (HtmlNode item in liNodes)
{
    Console.WriteLine(item.InnerHtml);
    Console.WriteLine("获取每个li标签节点下面a标签的文本");
    string attributeTextContent = item.SelectSingleNode("./a").Attributes["href"].Value;
    string aTextContent = item.SelectSingleNode("./div[1]").InnerText;
    Console.WriteLine("a标签属性值:" + attributeTextContent);
    Console.WriteLine("a标文本值:" + aTextContent);
}
  • 4.下载文件
 /// <summary>
/// 请求文件流
/// </summary>
public static bool DoFileStream(string pathUrl,string path,string fileName)
{
    try
    {
        System.Net.HttpWebRequest request = null;
        System.Net.HttpWebResponse response = null;
        //请求网络路径地址
        request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
        //超时时间
        request.Timeout = 5000; 
        //获得请求结果
        response = (System.Net.HttpWebResponse)request.GetResponse();

        //如果不存在就创建file文件夹
        if (!Directory.Exists(path))
        {
            if (path != null) Directory.CreateDirectory(path);
        }
        //下载的文件路径
        path = path + fileName;
        Stream stream = response.GetResponseStream();
        //先创建文件
        Stream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Create);
        byte[] fileByte = new byte[1024];
        int total = stream.Read(fileByte, 0, fileByte.Length);
        while (total > 0)
        {
            //之后再输出内容
            fileStream.Write(fileByte, 0, total);
            total = stream.Read(fileByte, 0, fileByte.Length);
        }
        fileStream.Close();
        fileStream.Dispose();
        stream.Close();
        stream.Dispose();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}
  • 备注
    注意路径里一个"/“表示只查找第一层跟节点;”//“表示所有节点都查找;”./"表示从当前结点而不是根结点开始查找

分享一下代码

链接:https://pan.baidu.com/s/1qMmHH9OPlO0Hb4Yw0FBIuw
提取码:o4qf

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值