爬虫

  • 扩展
    • 优势
    • 传送门
  • HtmlAgilityPac简单使用
    • A.网页源码
    • B.操作DOM元素
  • 分享一下代码

扩展

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

优势

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

传送门

  • 官网地址
  • Github开源代码地址

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

C# 爬虫(学习笔记)相关推荐

  1. 爬虫学习笔记(十)—— Scrapy框架(五):下载中间件、用户/IP代理池、settings文件

    一.下载中间件 下载中间件是一个用来hooks进Scrapy的request/response处理过程的框架. 它是一个轻量级的底层系统,用来全局修改scrapy的request和response. ...

  2. Python3 爬虫学习笔记 C18【爬虫框架 pyspider — 深入理解】

    Python3 爬虫学习笔记第十八章 -- [爬虫框架 pyspider - 深入理解] 文章目录 [18.1]启动参数 [18.2]运行单个组件 [18.2.1]运行 Scheduler [18.2 ...

  3. Python3 爬虫学习笔记 C17【爬虫框架 pyspider — 基本使用】

    Python3 爬虫学习笔记第十七章 -- [爬虫框架 pyspider - 基本使用] 文章目录 [17.1]初识 pyspider [17.2]使用 pyspider [17.2.1]主界面 [1 ...

  4. Python3 爬虫学习笔记 C16【数据储存系列 — Redis】

    Python3 爬虫学习笔记第十六章 -- [数据储存系列 - Redis] 文章目录 [16.1]关于 Redis [16.2]使用 Redis [16.3]Key(键)操作 [16.4]Strin ...

  5. Python3 爬虫学习笔记 C15【代理的基本使用】

    Python3 爬虫学习笔记第十五章 -- [代理的基本使用] 文章目录 [15.1]代理初识 [15.2]urllib 库使用代理 [15.3]requests 库使用代理 [15.4]Seleni ...

  6. Python3 爬虫学习笔记 C14【验证码对抗系列 — 点触验证码】

    Python3 爬虫学习笔记第十四章 -- [验证码对抗系列 - 点触验证码] 文章目录 [14.1]关于点触验证码 [14.2]点触验证码攻克思路 [14.3]模拟登录 12306 - 总体思路 [ ...

  7. Python3 爬虫学习笔记 C13【验证码对抗系列 — 滑动验证码】

    Python3 爬虫学习笔记第十三章 -- [验证码对抗系列 - 滑动验证码] 文章目录 [13.1]关于滑动验证码 [13.2]滑动验证码攻克思路 [13.3]模拟登录 bilibili - 总体思 ...

  8. Python3 爬虫学习笔记 C12【验证码对抗系列 — 图形验证码】

    Python3 爬虫学习笔记第十二章 -- [验证码对抗系列 - 图形验证码] 文章目录 [12.1]关于普通图形验证码 [12.2]tesserocr 库识别验证码 [12.3]pytesserac ...

  9. Python3 爬虫学习笔记 C11【数据储存系列 — MongoDB】

    Python3 爬虫学习笔记第十一章 -- [数据储存系列 - MongoDB] 文章目录 [11.1]关于 MongoDB [11.2]MongoDB 基本操作语句 [11.3]连接 MongoDB ...

  10. Python3 爬虫学习笔记 C10【数据储存系列 — MySQL】

    Python3 爬虫学习笔记第十章 -- [数据储存系列 - MySQL] 文章目录 [10.1]MySQL 基本操作语句 数据库操作 表操作 表的结构 表的数据 [10.2]Python 连接 My ...

最新文章

  1. 时间序列预测——线性回归(上下界、异常检测),异常检测时候历史数据的输入选择是关键,使用过去历史值增加模型健壮性...
  2. python importerror怎么解决-解决python有时候import不了当前的包问题
  3. hbase shell中命令无法删除?
  4. 《scikit-learn》决策树之鸢尾花分类
  5. ffmpeg 从内存中读取数据(或将数据输出到内存)
  6. Selenium爬虫 -- 使用Selenium爬取数据时,网页切换之后原先获取的元素变量失效的问题
  7. (数据挖掘-入门-4)基于物品的协同过滤
  8. 医学专业学语文数学英语计算机嚒,医学专业到底有哪些一级学科,你知道吗?...
  9. NOIP模拟题——复制粘贴2
  10. 如何免费使用xshell、xftp工具
  11. Effective C++ item 6
  12. JavaScript基础及画布
  13. 在Chrome安装Edge的插件
  14. 计算机学院写论文格式,写作计算机论文的标准格式是什么
  15. linux 运行脚本时报错:语法错误: 未预期的文件结尾
  16. Session会话管理
  17. 蓝桥杯JAVA-7.集合(容器)在竞赛中的使用
  18. Migrating from REDWOOD CRONACLE TO CA WORKLOAD AUTOMATION GUIDE
  19. ARP工作原理以及ARP欺骗、中间人攻击
  20. 把复杂的事做简单,这是一种本事

热门文章

  1. 字节跳动历年校招Android面试真题解析,大厂直通车!
  2. 基于centos7安装多实例mysql8.0完整版(超级详细)
  3. 『 Spark 』1. spark 简介
  4. 创造发挥能力的魔幻空间
  5. 联想笔记本系统更新中断后变成蓝屏怎么U盘重装系统?
  6. 星辰天合参加首届数字驱动创新峰会 强调以 SDS 加速数据基础设施建设
  7. C#下的一个好用的日历库(sxtwl_cpp),支持农历转公历,和公历转农历等功能
  8. 奔驰EQE SUV:四驱标配,续航613km,售价48.6万起
  9. BGP BFD测试案例
  10. 广州app定制开发:常见的app推广有哪些途径?