这个版本主要是以百度图片为对象,对其进行爬虫操作,实现了最基本的下载功能,但是缺陷非常多,日后还会对其进行改进。

打开百度图片,同时打开开发者工具,我们会发现,百度图片是通过如下的一段ajax来加载图片的。

http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1466428638972_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%94%90%E5%AB%A3&f=3&oq=tangyan&rsp=0

这里,我们只需了解word后面就是我们的关键字,那么,这个就比较好弄了,结合一部分V1.0的代码,很快就可以开发出来,原理和V1.0类似。

后台代码如下:

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.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text.RegularExpressions; namespace 针对百度图片的动态网页爬虫
{
public partial class Form1 : Form
{
static int count = ;
public Form1()
{
InitializeComponent();
} private void btnDo_Click(object sender, EventArgs e)
{
int pageCount=;
string keyword = this.keyWords.Text;
for (int i = ; i <pageCount; i++)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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="+keyword.ToString());
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
try
{
// 下载指定页的所有图片
DownloadPage(stream);
}
catch (Exception ex)
{
// 跨线程访问UI线程的txtLogs }
}
}
else
{
// MessageBox.Show("获取第" + pageCount + "页失败:" + response.StatusCode);
}
}
}
MessageBox.Show("执行成功,共"+count.ToString()+"图片");
}
private static string[] getLinks(string html)
{
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++;
} }
return links;
}
private void DownloadPage(Stream stream)
{
using(StreamReader reader=new StreamReader(stream))
{
string r1;
StringBuilder sb = new StringBuilder();
while((r1=reader.ReadLine())!=null)
{
sb.Append(r1);
}
FileStream aFile = new FileStream("../../txt.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);//将网页存储到了txt文本文件中
sw.WriteLine(sb.ToString());
sw.Close();
string[] s;
s = getLinks(sb.ToString());
int i = ; for(i=;i<s.Count();i++)
{
if(s[i]!=null||s[i]!="")
{
count++;
savePicture(s[i]);
} }
this.label2.Text = count.ToString();
}
}
private static bool isValiable(string url)
{
if (url.Contains(".jpg") || url.Contains(".gif") || url.Contains(".png"))
{
return true; //得到一些图片之类的资源
}
return false;
}
private static void savePicture(string path)
{
DataClasses1DataContext db = new DataClasses1DataContext();
Uri url = new Uri(path);
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Referer = "http://image.baidu.com";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); 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();
} }
}
}

演示效果:

这个程序只是解决了有无得问题,还有许多问题,以后会继续解决。

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

  1. co-dialog弹出框组件-版本v2.0.0

    co-dialog theme 访问git:co-dialog 版本v2.0.0 主题2 coog.app('.theme2').use({ title: 'JUST CHECKING.', mess ...

  2. 湖南师范大学计算机基础课网络教学平台 版本 V2.0(2017.9.18)

    湖南师范大学计算机基础课网络教学平台 版本 V2.0(2017.9.18) 开发环境: 开发工具:VS2013,数据库:Sqlserver2012 开发语言:Asp.net MVC5 ,界面UI:jq ...

  3. co-dialog弹出框组件-版本v2.0.1

    具体案例查看co-dialog:https://koringz.github.io/co-dialog/index.html 2.0.1版本优化项,代码压缩,修复PC和移动端自适应,修复显示弹出框浏览 ...

  4. Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration info

    Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the ...

  5. 微信快速开发框架(六)-- 微信快速开发框架(WXPP QuickFramework)V2.0版本上线--源码已更新至github

    4月28日,已增加多媒体上传及下载API,对应MediaUploadRequest和MediaGetRequest ------------------------------------------ ...

  6. [python]新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  7. Python爬虫02——贴吧图片爬虫V2.0

    Python小爬虫——贴吧图片爬虫V2.0 贴吧图片爬虫进阶:在上次的第一个小爬虫过后,用了几次发现每爬一个帖子,都要自己手动输入帖子链接,WTF这程序简直反人类!不行了不行了得改进改进. 思路: 贴 ...

  8. (转)新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  9. springboot v2.0.3版本多数据源配置

    本篇分享的是springboot多数据源配置,在从springboot v1.5版本升级到v2.0.3时,发现之前写的多数据源的方式不可用了,捕获错误信息如: 异常:jdbcUrl is requir ...

随机推荐

  1. windows下 安装Kali Linux到 U盘的方法

    作者:玄魂工作室 \ 2016年10月20日 把Kali Linux安装到U盘好处很多,可以从U盘启动使用整个电脑的硬件资源, 可以随身携带,减少对自己电脑的影响. 今天要给大家讲的是如何在windo ...

  2. PC使用网线上网的条件下,通过PC的Wifi共享提供手机上网教程

    场景和目标 你有一个笔记本(或装有无线网卡的PC),可以通过网线上网,但是没有无线路由器.现在想要通过笔记本的无线网,让手机也能共享wifi上网. 环境 Win7 操作系统.带有无线网卡的PC或笔记本 ...

  3. Android学习——windows下搭建NDK_r9环境

    1. NDK(Native Development Kit) 1.1 NDK简介 Android NDK是一套允许开发人员使用本地代码(如C/C++)进行Android APP功能开发的工具,通过这个 ...

  4. 前nginx后Apache+Node反向代理

    前几天一直在被一个问题困扰,机器上跑的站点太多了,Apache上面有十几个,NodeJS的也有一堆,记端口号都要烦死,于是萌生了使用反向代理的想法.出发点貌似太low了,完全不是出于负载均衡.高并发什 ...

  5. 【原】Telerik radwindow 在IE10下偶尔报 unable to get value of the property 'toLowerCase' 的解决办法

    笔者正在开发的新项目在升级了最新版本的Telerik Control和决定支持IE10后,遇到了一个很棘手的问题,偶尔会在打开Radwindow的时候报JS error :unable to get ...

  6. LInux MySQL 数据库 的一些操作

    数据库安装: ………… 创建数据库连接新用户: 1.登录mysql #mysql -u root -p 2.新增用户 insert into mysql.user(Host,User,Password ...

  7. Java基础-输入输出-2.编写IoDemo.java的Java应用程序,程序完成的功能是:首先读取text.txt文件内容,再通过键盘输入文件的名称为iodemo.txt,把text.txt的内容存入iodemo.txt

    2.编写IoDemo.java的Java应用程序,程序完成的功能是:首先读取text.txt文件内容,再通过键盘输入文件的名称为iodemo.txt,把text.txt的内容存入iodemo.txt ...

  8. 【转】批量复制操作(SqlBulkCopy)的出错处理:事务提交、回滚

    原文地址:http://blog.csdn.net/westsource/article/details/6658109 默认情况下,批量复制操作作为独立的操作执行. 批量复制操作以非事务性方式发生, ...

  9. js实现匀速运动及透明度动画

    1.html代码 <body> <div id="container"> <span id="btn"></span& ...

  10. Unity3D知识框架

    美术部分:           3d模型,材质,纹理,shader,Animator,Animation,天空盒,灯光效果,烘焙 程序部分:           基本组成:               ...