这次是对2.0的小修补,2.0交互几乎没有,这次添加了进度条,和文本框,同时由于取得的链接主要会出现错误是:webResponse错误。

针对这种情况,设置了

 try
{
webResponse = (HttpWebResponse)webRequest.GetResponse();
}
catch(WebException ex)
{
webResponse = (HttpWebResponse)ex.Response;
}

截取错误信息,这里我们不处理,后续直接判定statecode属性来决定是否还要执行下面的程序。

另外一点变化就是以前是通过将所获取的网页存到文本中去,这次

WebRequest myRequest = WebRequest.Create("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1466307565574_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=" + Uri.EscapeDataString(keyWord));
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
if (myResponse.StatusCode == HttpStatusCode.OK)
{
Stream strm = myResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string line = sr.ReadToEnd();

将它全放入了string中。

最后一点是去掉了DownloadPage这个方法,如上,它的功能可以放入按钮的单击事件中实现,没有必要把一件事做两遍。

下面是前台页面:

后台代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms; namespace 百度图片爬虫V2._1
{
public partial class Form1 : Form
{
public delegate void AsynFunction(string s,int i);
public Form1()
{
InitializeComponent();
}
private static string[] getLinks(string html, out int counts)
{
const string pattern = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //新建正则模式
MatchCollection m = r.Matches(html); //获得匹配结果
string[] links = new string[m.Count];
int count = ;
for (int i = ; i < m.Count; i++)
{
if (isValiable(m[i].ToString()))
{
links[count] = m[i].ToString(); //提取出结果
count++;
} }
counts = count;
return links;
}
private void button1_Click(object sender, EventArgs e)
{
string keyWord = this.textBox1.Text;
WebRequest myRequest = WebRequest.Create("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1466307565574_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=" + Uri.EscapeDataString(keyWord));
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
if (myResponse.StatusCode == HttpStatusCode.OK)
{
Stream strm = myResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string line = sr.ReadToEnd();
int counts = ;
string[] str = getLinks(line, out counts);
this.progressBar1.Maximum = counts;
for (int i = ; i < counts; i++)
{
AsynFunction fun = new AsynFunction(savePicture);
fun.BeginInvoke(str[i],i, ar => {
fun.EndInvoke(ar);
this.progressBar1.BeginInvoke(new Action(() =>
{
this.progressBar1.Value =progressBar1.Maximum;
}));
this.textBox2.BeginInvoke(new Action(() =>
{
StringBuilder sb=new StringBuilder();
sb.Append(Environment.NewLine);
// sb.Append(str[i].ToString());
sb.Append("下载结束");
this.textBox2.Text += sb.ToString();
}));
}, fun);
}
}
}
private static bool isValiable(string url)
{
if (url.Contains(".jpg") || url.Contains(".gif") || url.Contains(".png"))
{
return true; //得到一些图片之类的资源
}
return false;
}
public void savePicture(string path,int i)
{
if (path != "" && path != null)
{
DataClasses1DataContext db = new DataClasses1DataContext();
Uri url = new Uri(path);
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Referer = "http://image.baidu.com";
webRequest.Timeout = ;
//设置连接超时时间
webRequest.AllowAutoRedirect = true;
webRequest.Headers.Set("Pragma", "no-cache");
webRequest.UserAgent = "Mozilla-Firefox-Spider(Wenanry)";
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.GetResponse();
}
catch(WebException ex)
{
webResponse = (HttpWebResponse)ex.Response;
} if(webResponse!=null&&webResponse.StatusCode==HttpStatusCode.OK)
{ if (isValiable(path))//判断如果是图片,就将其存储到数据库中。
{
Bitmap myImage = new Bitmap(webResponse.GetResponseStream()); MemoryStream ms = new MemoryStream();
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
var p = new pictureUrl
{
pictureUrl1 = ms.ToArray()
};
db.pictureUrl.InsertOnSubmit(p);
db.SubmitChanges();
this.progressBar1.BeginInvoke(new Action(() =>
{
this.progressBar1.Value = i;
}));
this.textBox2.BeginInvoke(new Action(() =>
{
StringBuilder sb1 = new StringBuilder();
sb1.Append(path);
sb1.Append("图片下载开始" + Environment.NewLine);
this.textBox2.Text += sb1.ToString();
}));
}
}
}
} private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

C#写爬虫,版本V2.1的更多相关文章

  1. [Python]新手写爬虫全过程(已完成)

    今天早上起来,第一件事情就是理一理今天该做的事情,瞬间get到任务,写一个只用python字符串内建函数的爬虫,定义为v1.0,开发中的版本号定义为v0.x.数据存放?这个是一个练手的玩具,就写在tx ...

  2. [Python]新手写爬虫全过程(转)

    今天早上起来,第一件事情就是理一理今天该做的事情,瞬间get到任务,写一个只用python字符串内建函数的爬虫,定义为v1.0,开发中的版本号定义为v0.x.数据存放?这个是一个练手的玩具,就写在tx ...

  3. ECSHOP 数据库结构说明 (适用版本v2.7.3)

    ECSHOP 数据库结构说明 (适用版本v2.7.3) 1.account_log 用户账目日志表 字段 类型 Null/默认 注释 log_id mediumint(8) 否 / 自增 ID 号 u ...

  4. 手把手教你用.NET Core写爬虫

    写在前面 自从上一个项目58HouseSearch从.NET迁移到.NET core之后,磕磕碰碰磨蹭了一个月才正式上线到新版本. 然后最近又开了个新坑,搞了个Dy2018Crawler用来爬dy20 ...

  5. 用go写爬虫服务并发请求,限制并发数

    java写爬虫服务,思路是线程池,任务队列,限制并行线程数即可. go要用另一种设计思路,不能在线程层面限制,协程的异步请求,如果不作处理,并行发出所有网络请求,因网络请求数过多,会抛出异常 低版本的 ...

  6. 让你从零开始学会写爬虫的5个教程(Python)

    写爬虫总是非常吸引IT学习者,毕竟光听起来就很酷炫极客,我也知道很多人学完基础知识之后,第一个项目开发就是自己写一个爬虫玩玩. 其实懂了之后,写个爬虫脚本是很简单的,但是对于新手来说却并不是那么容易. ...

  7. scrapy写爬虫是出现no module named win32api错误

    windows下利用scrapy(python2.7)写爬虫,运行 scrapy crawl dmoz 命令时提示:exceptions.ImportError: No module named wi ...

  8. PHP, Python, Node.js 哪个比较适合写爬虫?

    PHP, Python, Node.js 哪个比较适合写爬虫? 1.对页面的解析能力2.对数据库的操作能力(mysql)3.爬取效率4.代码量推荐语言时说明所需类库或者框架,谢谢.比如:python+ ...

  9. 怎么用Python写爬虫抓取网页数据

    机器学习首先面临的一个问题就是准备数据,数据的来源大概有这么几种:公司积累数据,购买,交换,政府机构及企业公开的数据,通过爬虫从网上抓取.本篇介绍怎么写一个爬虫从网上抓取公开的数据. 很多语言都可以写 ...

  10. python写爬虫时的编码问题解决方案

    在使用Python写爬虫的时候,常常会遇到各种令人抓狂的编码错误问题.下面给出一些简单的解决编码错误问题的思路,希望对大家有所帮助. 首先,打开你要爬取的网站,右击查看源码,查看它指定的编码是什么,如 ...

随机推荐

  1. 作业六:团队项目——编写项目的Spec

    主要内容: 各组结合所选项目,编写项目的规格说明书(Spec),Spec应至少包含以下内容:(20分) 1. Spec的目标 2. 项目的典型用户和场景 3. 项目的用例模型 4. 项目中涉及到的术语 ...

  2. 细说 Data URI

    Data URL 早在 1995 年就被提出,那个时候有很多个版本的 Data URL Schema 定义陆续出现在 VRML 之中,随后不久,其中的一个版本被提上了议案——将它做个一个嵌入式的资源放 ...

  3. Silverlight和WPF中DataContractJsonSerializer对时间的处理差异

    原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com Silverlight脱胎于WPF,他们的行为不完全并不完全相同,DataContractJsonSerializ ...

  4. MyISAM和InnoDB

    MyISAM和InnoDB MyISAM MyISAM使用B+tree作为索引结构,叶节点存放的是数据地址. MyISAM不支持事务和外键. MyISAM是表锁,对数据库写操作时会锁住整个表,效率低. ...

  5. 备忘-Android ViewPager 子页监听事件

    @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(mListViews ...

  6. 深圳本土web前端经验交流

    群号:125776555  深圳本土web前端技术交流群 baidu tencent前端拒绝垃圾广告.吹水,欢迎讨论技术.跳槽经验期待您的加入 

  7. TODO:小程序的春天你想做什么

    TODO:小程序的春天你想做什么 微信小程序是一种全新的连接用户与服务的方式,它可以在微信内被便捷地获取和传播,同时具有出色的使用体验. 初步了解小程序的特点 导航明确,来去自如 统一稳定, 视觉规范 ...

  8. react-native环境搭建

    目标平台 Android 开发平台 windows 开发环境安装建议:由于开发环境存在差异,建议参照react官网 或者react中文网 安装, react-native -- 在Windows下搭建 ...

  9. 动态加载JS 和 CSS

    <script type="text/javascript"> $(function () { var filename = '/assets/css/main.css ...

  10. vue小总结

    以下是我在使用vue过程中自己对vue的一些小总结,希望对学习vue的亲们能有所帮助: 1.   http的post请求: this.$http({url: '/someUrl', method: ' ...