HTTP请求工具类(功能:1、获取网页html;2、下载网络图片;):

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Utils
{
/// <summary>
/// HTTP请求工具类
/// </summary>
public class HttpRequestUtil
{
/// <summary>
/// 获取页面html
/// </summary>
public static string GetPageHtml(string url)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
} /// <summary>
/// Http下载文件
/// </summary>
public static void HttpDownloadFile(string url, int minWidth, int minHeight)
{
int pos = url.LastIndexOf("/") + ;
string fileName = url.Substring(pos);
string path = Application.StartupPath + "\\download";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePathName = path + "\\" + fileName;
if (File.Exists(filePathName)) return; // 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";
request.Proxy = null;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream(); MemoryStream memoryStream = new MemoryStream();
byte[] bArr = new byte[];
int size = responseStream.Read(bArr, , (int)bArr.Length);
while (size > )
{
memoryStream.Write(bArr, , size);
size = responseStream.Read(bArr, , (int)bArr.Length);
}
Image tempImage = System.Drawing.Image.FromStream(memoryStream, true);
int imageHeight = tempImage.Height;
int imageWidth = tempImage.Width;
if (imageHeight >= minHeight && imageWidth >= minWidth)
{
memoryStream.Seek(, SeekOrigin.Begin);
size = memoryStream.Read(bArr, , (int)bArr.Length);
FileStream fs = new FileStream(filePathName, FileMode.Create);
while (size > )
{
fs.Write(bArr, , size);
size = memoryStream.Read(bArr, , (int)bArr.Length);
}
fs.Close();
}
memoryStream.Close();
responseStream.Close();
}
}
}

VisitedHelper类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Utils
{
/// <summary>
/// 已访问的网址列表
/// </summary>
public class VisitedHelper
{
private static List<string> m_VisitedList = new List<string>(); #region 判断是否已访问
/// <summary>
/// 判断是否已访问
/// </summary>
public static bool IsVisited(string url)
{
if (m_VisitedList.Exists(a => a == url))
{
return true;
}
return false;
}
#endregion #region 添加已访问
/// <summary>
/// 添加已访问
/// </summary>
public static void Add(string url)
{
m_VisitedList.Add(url);
}
#endregion }
}

多线程爬取网页代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils; namespace 爬虫
{
public partial class Form1 : Form
{
private static int m_MinWidth = ;
private static int m_MinHeight = ;
private static int m_CompletedCount = ; public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(, );
int.TryParse(txtMinWidth.Text, out m_MinWidth);
int.TryParse(txtMinHeight.Text, out m_MinHeight);
button1.Enabled = false;
lblMsg.Text = "正在爬取图片…";
timer1.Start();
new Thread(new ThreadStart(delegate()
{
Crawling(txtUrl.Text, null);
})).Start();
} /// <summary>
/// 爬取
/// </summary>
private void Crawling(string url, string host)
{
if (!VisitedHelper.IsVisited(url))
{
VisitedHelper.Add(url); if (host == null)
{
host = GetHost(url);
} string pageHtml = HttpRequestUtil.GetPageHtml(url);
Regex regA = new Regex(@"<a[\s]+[^<>]*href=(?:""|')([^<>""']+)(?:""|')[^<>]*>[^<>]+</a>", RegexOptions.IgnoreCase);
Regex regImg = new Regex(@"<img[\s]+[^<>]*src=(?:""|')([^<>""']+(?:jpg|jpeg|png|gif))(?:""|')[^<>]*>", RegexOptions.IgnoreCase); MatchCollection mcImg = regImg.Matches(pageHtml);
foreach (Match mImg in mcImg)
{
string imageUrl = mImg.Groups[].Value;
try
{
int imageWidth = GetImageWidthOrHeight(mImg.Value, true);
int imageHeight = GetImageWidthOrHeight(imageUrl, false);
if (imageWidth >= m_MinWidth && imageHeight >= m_MinHeight)
{
if (imageUrl.IndexOf("javascript") == -)
{
if (imageUrl.IndexOf("http") == )
{
HttpRequestUtil.HttpDownloadFile(imageUrl, m_MinWidth, m_MinHeight);
}
else
{
HttpRequestUtil.HttpDownloadFile(host + imageUrl, m_MinWidth, m_MinHeight);
}
}
}
}
catch { }
} //递归遍历
MatchCollection mcA = regA.Matches(pageHtml);
foreach (Match mA in mcA)
{
try
{
string nextUrl = mA.Groups[].Value;
if (nextUrl.IndexOf("javascript") == -)
{
if (nextUrl.IndexOf("http") == )
{
if (GetHost(url) == host)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj)
{
try
{
Crawling(nextUrl, host);
m_CompletedCount++;
}
catch { }
}));
}
}
else
{
if (GetHost(url) == host)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj)
{
try
{
Crawling(host + nextUrl, host);
m_CompletedCount++;
}
catch { }
}));
}
}
}
}
catch { }
}
}
} //end Crawling方法 /// <summary>
/// 获取主机
/// </summary>
private string GetHost(string url)
{
Regex regHost = new Regex(@"(?:http|https)://[a-z0-9\-\.:]+", RegexOptions.IgnoreCase);
Match mHost = regHost.Match(url);
return mHost.Value + "/";
} //计时器事件
private void timer1_Tick(object sender, EventArgs e)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
if (workerThreads == && m_CompletedCount > )
{
lblMsg.Text = "已结束";
}
else
{
lblMsg.Text = "正在爬取图片…";
}
} /// <summary>
/// 获取图片宽度或高度
/// </summary>
private int GetImageWidthOrHeight(string imageTagString, bool isWidth)
{
string tag = isWidth ? "width" : "height";
Regex reg = new Regex(string.Format(@"{0}=""([\d\.]+)""", tag), RegexOptions.IgnoreCase);
Match match = reg.Match(imageTagString);
if (match.Success)
{
return (int)Convert.ToDouble(match.Groups[].Value);
}
else
{
reg = new Regex(string.Format(@"{0}[\s]*:[\s]*([\d\.]+)[\s]*px[\s]*;", tag), RegexOptions.IgnoreCase);
match = reg.Match(imageTagString);
if (match.Success)
{
return (int)Convert.ToDouble(match.Groups[].Value);
}
}
return int.MaxValue;
} } //end Form1类 /// <summary>
/// 跨线程访问控件的委托
/// </summary>
public delegate void InvokeDelegate();
}

截图:

C#实现网页爬虫的更多相关文章

  1. cURL 学习笔记与总结(2)网页爬虫、天气预报

    例1.一个简单的 curl 获取百度 html 的爬虫程序(crawler): spider.php <?php /* 获取百度html的简单网页爬虫 */ $curl = curl_init( ...

  2. c#网页爬虫初探

    一个简单的网页爬虫例子! html代码: <head runat="server"> <title>c#爬网</title> </head ...

  3. 网页爬虫--scrapy入门

    本篇从实际出发,展示如何用网页爬虫.并介绍一个流行的爬虫框架~ 1. 网页爬虫的过程 所谓网页爬虫,就是模拟浏览器的行为访问网站,从而获得网页信息的程序.正因为是程序,所以获得网页的速度可以轻易超过单 ...

  4. 网页爬虫的设计与实现(Java版)

    网页爬虫的设计与实现(Java版)     最近为了练手而且对网页爬虫也挺感兴趣,决定自己写一个网页爬虫程序. 首先看看爬虫都应该有哪些功能. 内容来自(http://www.ibm.com/deve ...

  5. Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)

    原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开 ...

  6. [resource-]Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱

    reference: http://www.52nlp.cn/python-%e7%bd%91%e9%a1%b5%e7%88%ac%e8%99%ab-%e6%96%87%e6%9c%ac%e5%a4% ...

  7. 网页抓取:PHP实现网页爬虫方式小结

    来源:http://www.ido321.com/1158.html 抓取某一个网页中的内容,需要对DOM树进行解析,找到指定节点后,再抓取我们需要的内容,过程有点繁琐.LZ总结了几种常用的.易于实现 ...

  8. Java正则表达式--网页爬虫

    网页爬虫:其实就一个程序用于在互联网中获取符合指定规则的数据 爬取邮箱地址,爬取的源不同,本地爬取或者是网络爬取 (1)爬取本地数据: public static List<String> ...

  9. 从robots.txt開始网页爬虫之旅

    做个网页爬虫或搜索引擎(下面统称蜘蛛程序)的各位一定不会陌生,在爬虫或搜索引擎訪问站点的时候查看的第一个文件就是robots.txt了.robots.txt文件告诉蜘蛛程序在server上什么文件是能 ...

  10. Python网页爬虫(一)

    很多时候我们想要获得网站的数据,但是网站并没有提供相应的API调用,这时候应该怎么办呢?还有的时候我们需要模拟人的一些行为,例如点击网页上的按钮等,又有什么好的解决方法吗?这些正是python和网页爬 ...

随机推荐

  1. Wix 安装部署教程(九) --用WPF做安装界面

    经常安装PC端的应用,特别是重装系统之后,大致分为两类.一类像QQ,搜狗输入法这样的.分三步走的:第一个页面可以自定义安装路径和软件许可.第二个页面显示安装进度条,第三个页面推荐其他应用.先不管人家怎 ...

  2. [stm32] SIM808模块之发短信\GPS\TCP\HTTP研究

    SIM8008是四频模块,全球可用.含有TTL电平接口等接口,能够实现发短信.打电话.GPRS传输数据.GPS等功能.[正版资料请找beautifulzzzz·博客园] 一些细节: >> ...

  3. openseadragon.js与deep zoom java实现艺术品图片展示

    openseadragon.js 是一款用来做图像缩放的插件,它可以用来做图片展示,做展示的插件很多,也很优秀,但大多数都解决不了图片尺寸过大的问题. 艺术品图像展示就是最简单的例子,展示此类图片一般 ...

  4. Linux下安装Apache并以mod_wsgi方式部署django站点

    源码编译方式安装Apache 首先下载Apache源码压缩包,地址为http://mirror.bit.edu.cn/apache/httpd/ 继续下载apr和apr-util压缩包,地址为http ...

  5. 达洛克战记3 即将开服! What's New!

    历经数个月的开发,达洛克战记3即将全新开服! 剧情: 回归到三大种族起源时期,三大种族并没有像现在三足鼎立.人类一直处于统治地位.但是突然间一群巨人的出现,让人类损失惨重,身为勇者,需要探索巨人背后的 ...

  6. 2015 年最受 Linux 爱好者欢迎的软硬件大盘点

    Linux 爱好者都喜欢用哪些硬件,哪些发行版呢?近日 OpenBenchmarking.org 做了一个 2015 年度数据的统计和梳理,Linux Story 特意整理了一下,分享给大家. 转载于 ...

  7. Redis总结笔记(一):安装和常用命令

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/112.html?1455860824 一.redis简单介绍 redis是 ...

  8. PHP数据库操作:从MySQL原生API到PDO

    本文将举详细例子向大家展示PHP是如何使用MySQL原生API.MySQLi面向过程.MySQLi面向对象.PDO操作MySQL数据库的. 为了后面的测试,先建立数据库表test.包含表名user,s ...

  9. CAR

    24.编写一个Car类,具有String类型的属性品牌,具有功能drive: 定义其子类Aodi和Benchi,具有属性:价格.型号:具有功能:变速: 定义主类E,在其main方法中分别创建Aodi和 ...

  10. 制作Html标签以及表单、表格内容

    制作Html一般用DW(......),Html全称为(Hyper Text Markup Language   超文本标记语言) 文本就是平常电脑上的文本文档,只能存储文字,而超文本文档可以存储音乐 ...