.Net HttpWebRequest 爬虫核心爬取
1 爬虫,爬虫攻防
2 下载html
3 xpath解析html,获取数据和深度抓取(和正则匹配)
4 多线程抓取
熟悉http协议
提供两个方法Post和Get
public static string HttpGet(string url, Encoding encoding = null, Dictionary<string,string> headDic=null)
{
string html = string.Empty;
try
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
request.Timeout = * ;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
request.ContentType = "text/html; charset=utf-8";
if (headDic != null)
{
foreach (var item in headDic)
{
request.Headers.Add(item.Key, item.Value);
}
}
if(encoding==null)
encoding = Encoding.UTF8; // 如果是乱码就改成 utf-8 / GB2312
else
encoding=Encoding.GetEncoding("GB2312");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
log.Warn(string.Format("抓取{0}地址返回失败,response.StatusCode为{1}", url, response.StatusCode));
}
else
{
try
{
StreamReader sr = new StreamReader(response.GetResponseStream(), encoding);
html = sr.ReadToEnd();//读取数据
sr.Close();
}
catch (Exception ex)
{
log.Error(string.Format("DownloadHtml抓取{0}保存失败", url), ex);
html = null;
}
}
} }
catch (WebException ex)
{
if (ex.Message.Equals("远程服务器返回错误: (306)。"))
{
log.Error("远程服务器返回错误: (306)。", ex);
return null;
}
}
catch (Exception ex)
{
log.Error(string.Format("DownloadHtml抓取{0}出现异常", url), ex);
html = null;
}
return html;
}
/// <summary>
/// Post 调用借口
/// </summary>
/// <param name="url">接口地址</param>
/// <param name="value">接口参数</param>
/// <returns></returns>
public static string HttpPost(string url, string value)
{
string param = value;
Stream stream = null;
byte[] postData = Encoding.UTF8.GetBytes(param);
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = postData.Length;
stream = myRequest.GetRequestStream();
stream.Write(postData, , postData.Length); HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
if (myResponse.StatusCode == HttpStatusCode.OK)
{
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string rs = sr.ReadToEnd().Trim();
sr.Close();
return rs;
}
else
{
return "失败:Status:" + myResponse.StatusCode.ToString();
}
}
catch (Exception ex)
{
return "失败:ex:" + ex.ToString();
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
下载Html
StreamWriter sw = new StreamWriter("路径.txt", true, Encoding.GetEncoding("utf-8"));
sw.Write("爬取的html字符串");
sw.Close();
xpath
http://www.cnblogs.com/zhaozhan/archive/2009/09/09/1563617.html
http://www.cnblogs.com/zhaozhan/archive/2009/09/09/1563679.html
http://www.cnblogs.com/zhaozhan/archive/2009/09/10/1563703.html
正则匹配

目前使用起来最好用的正则
<title>(?<html>[\s\S]+?)</title> 意思是匹配 <title> *********</title>标签里面的任意字符串
Regex reTitle = new Regex(@"<title>(?<html>[\s\S]+?)</title>"/>");
string title = reTitle.Match(html).Groups["html"].Value;
多个选择
Regex rgInfo = new Regex(@"<td align=""left"">(?<company>[^<>]+)</td><td align=""center"">(?<id>[\dA-Z]+)</td><td align=""center"">(?<cat>[^<>]+)</td><td align=""center"">(?<grade>[A-Z]+)</td><td align=""center"">(?<date>[^\s&]*)");
MatchCollection mchInfos = rgInfo.Matches(strHtml);
foreach (Match m in mchInfos)
{
string strCompany = m.Groups["company"].Value;
string strId = m.Groups["id"].Value;
string strCat = m.Groups["cat"].Value.Replace(" ", "");
string grade = m.Groups["grade"].Value;
string date = m.Groups["date"].Value;
}
多线程
List<Task> taskList = new List<Task>();
TaskFactory taskFactory = new TaskFactory();
for(int i=;i<;i++)
{
taskList.Add(taskFactory.StartNew(Crawler));//将一个执行Crawler方法的线程放到集合里面,创建并启动 任务
if (taskList.Count > ) //线程池启动15个线程
{
taskList = taskList.Where(t => !t.IsCompleted && !t.IsCanceled && !t.IsFaulted).ToList();
Task.WaitAny(taskList.ToArray());//有线程执行完毕
}
}
Task.WaitAll(taskList.ToArray());//100个线程全部执行完成
Console.WriteLine("抓取全部完成 - -", DateTime.Now);
该文档只是自己记录,纯属记事本
.Net HttpWebRequest 爬虫核心爬取的更多相关文章
- 使用htmlparse爬虫技术爬取电影网页的全部下载链接
昨天,我们利用webcollector爬虫技术爬取了网易云音乐17万多首歌曲,而且还包括付费的在内,如果时间允许的话,可以获取更多的音乐下来,当然,也有小伙伴留言说这样会降低国人的知识产权保护意识,诚 ...
- [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)
转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...
- scrapy进阶(CrawlSpider爬虫__爬取整站小说)
# -*- coding: utf-8 -*- import scrapy,re from scrapy.linkextractors import LinkExtractor from scrapy ...
- 使用htmlparser爬虫技术爬取电影网页的全部下载链接
昨天,我们利用webcollector爬虫技术爬取了网易云音乐17万多首歌曲,而且还包括付费的在内,如果时间允许的话,可以获取更多的音乐下来,当然,也有小伙伴留言说这样会降低国人的知识产权保护意识,诚 ...
- scrapy-redis实现爬虫分布式爬取分析与实现
本文链接:http://blog.csdn.net/u012150179/article/details/38091411 一 scrapy-redis实现分布式爬取分析 所谓的scrapy-redi ...
- 网络爬虫之定向爬虫:爬取当当网2015年图书销售排行榜信息(Crawler)
做了个爬虫,爬取当当网--2015年图书销售排行榜 TOP500 爬取的基本思想是:通过浏览网页,列出你所想要获取的信息,然后通过浏览网页的源码和检查(这里用的是chrome)来获相关信息的节点,最后 ...
- python 爬虫之爬取大街网(思路)
由于需要,本人需要对大街网招聘信息进行分析,故写了个爬虫进行爬取.这里我将记录一下,本人爬取大街网的思路. 附:爬取得数据仅供自己分析所用,并未用作其它用途. 附:本篇适合有一定 爬虫基础 crawl ...
- Python爬虫之爬取慕课网课程评分
BS是什么? BeautifulSoup是一个基于标签的文本解析工具.可以根据标签提取想要的内容,很适合处理html和xml这类语言文本.如果你希望了解更多关于BS的介绍和用法,请看Beautiful ...
- python爬虫项目-爬取雪球网金融数据(关注、持续更新)
(一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_ ...
随机推荐
- VirtualBox创建VM结果ProcessorType是空的
用WMI来查询CPU的频率,一直没问题: "Select MaxClockSpeed From Win32_Processor Where ProcessorType = 3" 结 ...
- argument python 参数 举例
举例 例1:def multipute(x,y): x = 2 y[0] = ['spam'] return x,y X = 1 L = [1,2] X,L = multipute(X, L) pri ...
- Cordova插件相关常用命令
一,插件相关常用命令 1,查看所有已经安装的插件 1 cordova plugin ls 2,安装插件(以camera插件为例) 1 cordova plugin add cordova-plug ...
- angularJs-HelloWorld
AngularJS使用了不同的方法,它尝试去补足HTML本身在构建应用方面的缺陷.AngularJS通过使用我们称为标识符(directives)的结构,让浏览器能够识别新的语法. 1使用双大括号{{ ...
- html--<meta>设置缓存
html头文件设置常用之<meta>设置缓存 <meta http-equiv="pragma" content="no-cache"&g ...
- Spring当中的名称装配和类型装配有什么区别?
6 人赞同了该回答 Spring auto-wire的 五种方式:1:no 默认的方式是不进行自动装配,通过手工设置ref 属性来进行装配bean2:byName 通过参数名 自动装配,如果一个bea ...
- python正则表达提取文本好文
摘自: http://www.cnblogs.com/rj81/p/5933838.html
- BZOJ 1192 [HNOI2006]鬼谷子的钱袋:二进制 砝码称重问题
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1192 题意: 鬼谷子带了a元钱,他要把a元钱分装在小袋子中,使得任意不大于a的数目的钱,都 ...
- [算法]Trie树
我是好文章的搬运工,原文来自博客园,博主一线码农,选自”6天通吃树结构“系列,地址:http://www.cnblogs.com/huangxincheng/archive/2012/11/25/27 ...
- 【C++基础】重载,覆盖,隐藏
函数签名的概念 函数签名主要包括1.函数名:2.参数列表(参数的个数.数据类型和顺序):但是注意,C++官方定义中函数签名不包括返回值!! 1.重载 函数重载是指在同一作用域内,可以有一组具有相同函数 ...