C# HtmlAgilityPack爬取静态页面
最近对爬虫很感兴趣,稍微研究了一下,利用HtmlAgilityPack制作了一个十分简单的爬虫,这个简易爬虫只能获取静态页面的Html
HtmlAgilityPack简介
HtmlAgilityPack是一个解析速度十分快,并且开源的Html解析工具,并且HtmlAgilityPack支持使用Xpath解析Html,能够帮助我们解析Html文档就像解析Xml文档一样轻松、方便。
C#安装HtmlAgilityPack
- 如果VS安装有Nuget,在Nuget直接搜索安装即可。
- 下载后解压缩后有3个文件,这里只需要将其中的HtmlAgilityPack.dll、HtmlAgilityPack.xml引入解决方案中即可使用
实例(获取某页面图片)
加载HTML页面
//从网页中加载
string url = "https://www.bilibili.com";
HtmlWeb web = new HtmlWeb();
HtmlDocument hd = web.Load(url);
利用WebClient写一个图片下载器
需要using System.Net和using System.IO
/// <summary>
/// 图片下载器
/// </summary>
public class ImgDownloader
{
/// <summary>
/// 下载图片
/// </summary>
/// <param name="webClient"></param>
/// <param name="url">图片url</param>
/// <param name="folderPath">文件夹路径</param>
/// <param name="fileName">图片名</param>
public static void DownloadImg(WebClient webClient, string url, string folderPath, string fileName)
{
//如果文件夹不存在,则创建一个
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
//判断路径是否完整,补全不完整的路径
if (url.IndexOf("https:") == -1 && url.IndexOf("http:") == -1)
{
url = "https:" + url;
}
//下载图片
try
{
webClient.DownloadFile(url, folderPath + fileName);
Console.WriteLine(fileName + "下载成功");
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.WriteLine(url);
}
}
}
通过Xpath获取img标签中的图片
string imgPath = "//img";//选择img
int imgNum = 0;//图片编号
//获取img标签中的图片
foreach (HtmlNode node in hd.DocumentNode.SelectNodes(imgPath))
{
if (node.Attributes["src"] != null)
{
string imgUrl = node.Attributes["src"].Value.ToString();
if (imgUrl != "" && imgUrl != " ")
{
imgNum++;
//生成文件名,自动获取后缀
string fileName = imgNum + imgUrl.Substring(imgUrl.LastIndexOf("."));
ImgDownloader.DownloadImg(wc, imgUrl, "images/", fileName);
}
}
}
通过Xpath获取背景图
//获取背景图
string bgImgPath = "//*[@style]";//选择具有style属性的节点
foreach (HtmlNode node in hd.DocumentNode.SelectNodes(bgImgPath))
{
if (node.Attributes["style"].Value.Contains("background-image:url"))
{
imgNum++;
string bgImgUrl = node.Attributes["style"].Value;
bgImgUrl = Regex.Match(bgImgUrl, @"(?<=\().+?(?=\))").Value;//读取url()的内容
//Console.WriteLine(bgImgUrl);
//生成文件名,自动获取后缀
string fileName = imgNum + bgImgUrl.Substring(bgImgUrl.LastIndexOf("."));
ImgDownloader.DownloadImg(wc, bgImgUrl, "images/bgcImg/", fileName);
}
}
完整代码
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
namespace WebCrawlerDemo
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
string url = "https://www.bilibili.com";
HtmlWeb web = new HtmlWeb();
HtmlDocument hd = web.Load(url);//下载html页面
string imgPath = "//img";//选择img
int imgNum = 0;//图片编号
//获取img标签中的图片
foreach (HtmlNode node in hd.DocumentNode.SelectNodes(imgPath))
{
if (node.Attributes["src"] != null)
{
string imgUrl = node.Attributes["src"].Value.ToString();
if (imgUrl != "" && imgUrl != " ")
{
imgNum++;
//生成文件名,自动获取后缀
string fileName = imgNum + imgUrl.Substring(imgUrl.LastIndexOf("."));
ImgDownloader.DownloadImg(wc, imgUrl, "images/", fileName);
}
}
}
//获取背景图
string bgImgPath = "//*[@style]";//选择具有style属性的节点
foreach (HtmlNode node in hd.DocumentNode.SelectNodes(bgImgPath))
{
if (node.Attributes["style"].Value.Contains("background-image:url"))
{
imgNum++;
string bgImgUrl = node.Attributes["style"].Value;
bgImgUrl = Regex.Match(bgImgUrl, @"(?<=\().+?(?=\))").Value;//读取url()的内容
//生成文件名,自动获取后缀
string fileName = imgNum + bgImgUrl.Substring(bgImgUrl.LastIndexOf("."));
ImgDownloader.DownloadImg(wc, bgImgUrl, "images/bgcImg/", fileName);
}
}
Console.WriteLine("----------END----------");
Console.ReadKey();
}
}
/// <summary>
/// 图片下载器
/// </summary>
public class ImgDownloader
{
/// <summary>
/// 下载图片
/// </summary>
/// <param name="webClient"></param>
/// <param name="url">图片url</param>
/// <param name="folderPath">文件夹路径</param>
/// <param name="fileName">图片名</param>
public static void DownloadImg(WebClient webClient, string url, string folderPath, string fileName)
{
//如果文件夹不存在,则创建一个
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
//判断路径是否完整,补全不完整的路径
if (url.IndexOf("https:") == -1 && url.IndexOf("http:") == -1)
{
url = "https:" + url;
}
//下载图片
try
{
webClient.DownloadFile(url, folderPath + fileName);
Console.WriteLine(fileName + "下载成功");
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.WriteLine(url);
}
}
}
}
参考文章
C# HtmlAgilityPack爬取静态页面的更多相关文章
- Scrapy爬取静态页面
Scrapy爬取静态页面 安装Scrapy框架: Scrapy是python下一个非常有用的一个爬虫框架 Pycharm下: 搜索Scrapy库添加进项目即可 终端下: #python2 sudo p ...
- node js 爬虫爬取静态页面,
先打一个简单的通用框子 //根据爬取网页的协议 引入对应的协议, http||https var http = require('https'); //引入cheerio 简单点讲就是node中的jq ...
- scrapy模拟浏览器爬取验证码页面
使用selenium模块爬取验证码页面,selenium模块需要另外安装这里不讲环境的配置,我有一篇博客有专门讲ubuntn下安装和配置模拟浏览器的开发 spider的代码 # -*- coding: ...
- 一、python简单爬取静态网页
一.简单爬虫框架 简单爬虫框架由四个部分组成:URL管理器.网页下载器.网页解析器.调度器,还有应用这一部分,应用主要是NLP配合相关业务. 它的基本逻辑是这样的:给定一个要访问的URL,获取这个ht ...
- scrapy(四): 爬取二级页面的内容
scrapy爬取二级页面的内容 1.定义数据结构item.py文件 # -*- coding: utf-8 -*- ''' field: item.py ''' # Define here the m ...
- 爬取百度页面代码写入到文件+web请求过程解析
一.爬取百度页面代码写入到文件 代码示例: from urllib.request import urlopen #导入urlopen包 url="http://www.baidu.com& ...
- python爬虫爬取汽车页面信息,并附带分析(静态爬虫)
环境: windows,python3.4 参考链接: https://blog.csdn.net/weixin_36604953/article/details/78156605 代码:(亲测可以运 ...
- 使用HtmlAgilityPack爬取网站信息并存储到mysql
前言:打算做一个药材价格查询的功能,但刚开始一点数据都没有靠自己找信息录入的话很麻烦的,所以只有先到其它网站抓取存到数据库再开始做这个了. HtmlAgilityPack在c#里应该很多人用吧,简单又 ...
- node调用phantomjs-node爬取复杂页面
什么是phantomjs phantomjs官网是这么说的,'整站测试,屏幕捕获,自动翻页,网络监控',目前比较流行用来爬取复杂的,难以通过api或正则匹配的页面,比如页面是通过异步加载.phanto ...
随机推荐
- mybatis 获取新增数据的主键
<insert id="insert" parameterType="com.mmall.pojo.Shipping" useGeneratedKeys= ...
- HTML试题解析
1.关于CSS为什么会出现Bug说法不正确的是(). (选择二项) A:编写CSS样式时需要考虑在不同浏览器中实现表现一致 B:各大主流浏览器由于不同厂家开发,浏览器使用的内核不同,支持CSS的程度不 ...
- .getCellType()的几种类型值
CellType 类型 值 CELL_TYPE_NUMERIC 数值型 0 CELL_TYPE_STRING 字符串型 1 CELL_TYPE_FORMULA 公式型 2 CEL ...
- 第06组 Alpha冲刺(5/6)
队名:拾光组 组长博客链接 作业博客链接 团队项目情况 燃尽图(组内共享) 组长:宋奕 过去两天完成了哪些任务 主要完成了个人中心模块的接口设计 完善后端的信息处理 GitHub签入记录 接下来的计划 ...
- A3C 算法资料收集
A3C 算法资料收集 2019-07-26 21:37:55 Paper: https://arxiv.org/pdf/1602.01783.pdf Code: 1. 超级马里奥:https://gi ...
- Python17个常用内置模块总结
Python17个常用内置模块总结 1.getpass 2.os 3.sys 4.subprocess 5.hashlib 6.json 7.pickle 8.shutil 9.time 10.dat ...
- Linux下打开超大文件的方法
Linux下打开超大文件方法 在Linux下用VIM打开大小几个G.甚至几十个G的文件时,是非常慢的. 这时,我们可以利用下面的方法分割文件,然后再打开. 1 查看文件的前多少行 head -1000 ...
- 转 Shell判断字符串包含关系的几种方法
https://blog.csdn.net/rznice/article/details/71086839 Shell中判断字符串包含关系的方法: 1.通过grep来判断:12str1="a ...
- js时间的一些处理
1.判断是否为同一天 function isSameFay(t) { return new Date(t).toDateString() === new Date().toDateString(); ...
- laravel Carbon函数
原文地址:https://blog.csdn.net/lbwo001/article/details/53063867 carbon官方网站:https://carbon.nesbot.com/doc ...