最近对爬虫很感兴趣,稍微研究了一下,利用HtmlAgilityPack制作了一个十分简单的爬虫,这个简易爬虫只能获取静态页面的Html

HtmlAgilityPack简介

HtmlAgilityPack是一个解析速度十分快,并且开源的Html解析工具,并且HtmlAgilityPack支持使用Xpath解析Html,能够帮助我们解析Html文档就像解析Xml文档一样轻松、方便。

C#安装HtmlAgilityPack

  1. 如果VS安装有Nuget,在Nuget直接搜索安装即可。
  2. 下载后解压缩后有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爬取静态页面的更多相关文章

  1. Scrapy爬取静态页面

    Scrapy爬取静态页面 安装Scrapy框架: Scrapy是python下一个非常有用的一个爬虫框架 Pycharm下: 搜索Scrapy库添加进项目即可 终端下: #python2 sudo p ...

  2. node js 爬虫爬取静态页面,

    先打一个简单的通用框子 //根据爬取网页的协议 引入对应的协议, http||https var http = require('https'); //引入cheerio 简单点讲就是node中的jq ...

  3. scrapy模拟浏览器爬取验证码页面

    使用selenium模块爬取验证码页面,selenium模块需要另外安装这里不讲环境的配置,我有一篇博客有专门讲ubuntn下安装和配置模拟浏览器的开发 spider的代码 # -*- coding: ...

  4. 一、python简单爬取静态网页

    一.简单爬虫框架 简单爬虫框架由四个部分组成:URL管理器.网页下载器.网页解析器.调度器,还有应用这一部分,应用主要是NLP配合相关业务. 它的基本逻辑是这样的:给定一个要访问的URL,获取这个ht ...

  5. scrapy(四): 爬取二级页面的内容

    scrapy爬取二级页面的内容 1.定义数据结构item.py文件 # -*- coding: utf-8 -*- ''' field: item.py ''' # Define here the m ...

  6. 爬取百度页面代码写入到文件+web请求过程解析

    一.爬取百度页面代码写入到文件 代码示例: from urllib.request import urlopen #导入urlopen包 url="http://www.baidu.com& ...

  7. python爬虫爬取汽车页面信息,并附带分析(静态爬虫)

    环境: windows,python3.4 参考链接: https://blog.csdn.net/weixin_36604953/article/details/78156605 代码:(亲测可以运 ...

  8. 使用HtmlAgilityPack爬取网站信息并存储到mysql

    前言:打算做一个药材价格查询的功能,但刚开始一点数据都没有靠自己找信息录入的话很麻烦的,所以只有先到其它网站抓取存到数据库再开始做这个了. HtmlAgilityPack在c#里应该很多人用吧,简单又 ...

  9. node调用phantomjs-node爬取复杂页面

    什么是phantomjs phantomjs官网是这么说的,'整站测试,屏幕捕获,自动翻页,网络监控',目前比较流行用来爬取复杂的,难以通过api或正则匹配的页面,比如页面是通过异步加载.phanto ...

随机推荐

  1. Myschool试题

    题目: 1.查询所有学生记录,包含年级名称2.查询S1年级下的学生记录 一.com.myschool.dao 1 BaseDao package com.myschool.dao; import ja ...

  2. 为什么Map桶中个数超过8才转为红黑树

    这是笔者一个好友面试阿里时,被问及的一个问题,应该不少人看到这个问题都会一面懵逼.因为,大部分的文章都是分析链表是怎么转换成红黑树的,但是并没有说明为什么当链表长度为8的时候才做转换动作.笔者第一反应 ...

  3. 大数据应用期末总评——Hadoop综合大作业

    作业要求来自:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3339 Hadoop综合大作业 要求: 1.将爬虫大作业产生的csv文件 ...

  4. go -- go 程序 启动docker容器

    package main import ( "io" "log" "os" "time" "github.co ...

  5. ngxtop安装和使用

    监控nginx的请求信息,总共收到了多少个请求,有哪些成功的,有哪些失败的 ngxtop安装 1.安装python-pip 1) yum install epel-release 出现如下错误:No ...

  6. pypy安装与使用

    首先安装pypy环境: yum install pypy -y yum install pypy-devel -y 然后安装pypy的pip:wget https://bootstrap.pypa.i ...

  7. 大div套多个小div,怎样设置外div的高度自适应?

    在最后一个div 后面加上 overflow:hidden;如下: <div style="width:580px; height:auto; margin:0 auto; <d ...

  8. tensorflow到底难不难写

    发信人: xhsoldier01 (风大人), 信区: ITExpress 标 题: Re: 没有GPU,tensorflow,AI公司都得死掉 发信站: 水木社区 (Thu Oct 10 20:25 ...

  9. vue---数据列表过滤筛选

    使用vue进行数据过滤筛选是比较常用的功能,常见的使用场景就是搜索框数据筛选过滤了.简单示例: <template> <div> <input type="te ...

  10. Linux目录结构和作用

    转载自:https://blog.csdn.net/wangrongrongwq/article/details/79624797 [常见目录说明] 目录 /bin 存放二进制可执行文件(ls,cat ...