C# 网页图片采集
http://blog.csdn.net/a237428367/article/details/5987832
using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Net;
- using System.IO;
- using System.Windows.Forms;
- namespace ImageCollect
- {
- public class GatherPic
- {
- private string savePath;
- private string getUrl;
- private WebBrowser wb;
- private int iImgCount;
- //初始化参数
- public GatherPic(string sWebUrl, string sSavePath)
- {
- this.getUrl = sWebUrl;
- this.savePath = sSavePath;
- }
- //开始采集
- public bool start()
- {
- if (getUrl.Trim().Equals(""))
- {
- MessageBox.Show("哪来的虾米连网址都没输!");
- return false;
- }
- this.wb = new WebBrowser();
- this.wb.Navigate(getUrl);
- //委托事件
- this.wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
- return true;
- }
- //WebBrowser.DocumentCompleted委托事件
- private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
- {
- //页面里框架iframe加载完成不掉用SearchImgList()
- if (e.Url != wb.Document.Url) return;
- SearchImgList();
- }
- //检查出所有图片并采集到本地
- public void SearchImgList()
- {
- string sImgUrl;
- //取得所有图片地址
- HtmlElementCollection elemColl = this.wb.Document.GetElementsByTagName("img");
- this.iImgCount = elemColl.Count;
- foreach (HtmlElement elem in elemColl)
- {
- sImgUrl = elem.GetAttribute("src");
- //调用保存远程图片函数
- SaveImageFromWeb(sImgUrl, this.savePath);
- }
- }
- //保存远程图片函数
- public int SaveImageFromWeb(string imgUrl, string path)
- {
- string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
- path = path + "//" + imgName;
- string defaultType = ".jpg";
- string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
- string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
- foreach (string it in imgTypes)
- {
- if (imgType.ToLower().Equals(it))
- break;
- if (it.Equals(".bmp"))
- imgType = defaultType;
- }
- try
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
- request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
- request.Timeout = 10000;
- WebResponse response = request.GetResponse();
- Stream stream = response.GetResponseStream();
- if (response.ContentType.ToLower().StartsWith("image/"))
- {
- byte[] arrayByte = new byte[1024];
- int imgLong = (int)response.ContentLength;
- int l = 0;
- // CreateDirectory(path);
- FileStream fso = new FileStream(path, FileMode.Create);
- while (l < imgLong)
- {
- int i = stream.Read(arrayByte, 0, 1024);
- fso.Write(arrayByte, 0, i);
- l += i;
- }
- fso.Close();
- stream.Close();
- response.Close();
- return 1;
- }
- else
- {
- return 0;
- }
- }
- catch (WebException)
- {
- return 0;
- }
- catch (UriFormatException)
- {
- return 0;
- }
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Windows.Forms;
namespace ImageCollect
{
public class GatherPic
{
private string savePath;
private string getUrl;
private WebBrowser wb;
private int iImgCount;
//初始化参数
public GatherPic(string sWebUrl, string sSavePath)
{
this.getUrl = sWebUrl;
this.savePath = sSavePath;
}
//开始采集
public bool start()
{
if (getUrl.Trim().Equals(""))
{
MessageBox.Show("哪来的虾米连网址都没输!");
return false;
}
this.wb = new WebBrowser();
this.wb.Navigate(getUrl);
//委托事件
this.wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
return true;
}
//WebBrowser.DocumentCompleted委托事件
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//页面里框架iframe加载完成不掉用SearchImgList()
if (e.Url != wb.Document.Url) return;
SearchImgList();
}
//检查出所有图片并采集到本地
public void SearchImgList()
{
string sImgUrl;
//取得所有图片地址
HtmlElementCollection elemColl = this.wb.Document.GetElementsByTagName("img");
this.iImgCount = elemColl.Count;
foreach (HtmlElement elem in elemColl)
{
sImgUrl = elem.GetAttribute("src");
//调用保存远程图片函数
SaveImageFromWeb(sImgUrl, this.savePath);
}
}
//保存远程图片函数
public int SaveImageFromWeb(string imgUrl, string path)
{
string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
path = path + "//" + imgName;
string defaultType = ".jpg";
string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
foreach (string it in imgTypes)
{
if (imgType.ToLower().Equals(it))
break;
if (it.Equals(".bmp"))
imgType = defaultType;
}
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
request.Timeout = 10000;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
if (response.ContentType.ToLower().StartsWith("image/"))
{
byte[] arrayByte = new byte[1024];
int imgLong = (int)response.ContentLength;
int l = 0;
// CreateDirectory(path);
FileStream fso = new FileStream(path, FileMode.Create);
while (l < imgLong)
{
int i = stream.Read(arrayByte, 0, 1024);
fso.Write(arrayByte, 0, i);
l += i;
}
fso.Close();
stream.Close();
response.Close();
return 1;
}
else
{
return 0;
}
}
catch (WebException)
{
return 0;
}
catch (UriFormatException)
{
return 0;
}
}
}
}
调用方法
- GatherPic g = new GatherPic(“http://www.baidu.com”,"E:/XXX");
- g.start();
=====================================================
在web项目中使用WebBrowser类-----给网站抓图
最近做一个WEB项目,其中要求有个功能就是程序能网页抓图,举个例子: 在test.aspx页面上放一个TextBox和一个Button,TextBox用来输入要抓取的网页地址,然后按了Button之后,服务器要对前面输入的网址进行抓图,然后显示出来。我把抓图的业务逻辑做成一个类:
using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing; /// <summary>
/// WebSnap :网页抓图对象
/// </summary>
public class WebSnap2
{ public WebSnap2()
{
//
// TODO: 在此处添加构造函数逻辑
//
} /// <summary>
/// 开始一个抓图并返回图象
/// </summary>
/// <param name="Url">要抓取的网页地址</param>
/// <returns></returns>
public Bitmap StartSnap(string Url)
{
WebBrowser myWB = this.GetPage(Url);
Bitmap returnValue = this.SnapWeb(myWB);
myWB.Dispose();
return returnValue;
} private WebBrowser GetPage(string Url)
{
WebBrowser myWB = new WebBrowser();
myWB.ScrollBarsEnabled = false;
myWB.Navigate(Url);
while (myWB.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
return myWB;
} private Bitmap SnapWeb(WebBrowser wb)
{
HtmlDocument hd = wb.Document;
int height = Convert.ToInt32(hd.Body.GetAttribute("scrollHeight")) + ;
int width = Convert.ToInt32(hd.Body.GetAttribute("scrollWidth")) + ;
wb.Height = height;
wb.Width = width;
Bitmap bmp = new Bitmap(width, height);
Rectangle rec = new Rectangle();
rec.Width = width;
rec.Height = height;
wb.DrawToBitmap(bmp, rec);
return bmp;
} }
然后在test.asp的button_click事件里面调用:
WebSnap ws = new WebSnap();
Bitmap bmp= ws.StartSnap(TextBox1.Text);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.BinaryWrite(ms.GetBuffer());
C# 网页图片采集的更多相关文章
- 3D图片采集与展示(SurfaceView 自适应 Camera, 录制视频, 抽取帧)
最近在做一个3D图片采集与展示. 主要功能为:自定义Camera(google 已经摈弃了Camera, 推荐使用Camera2,后续篇幅,我将会用Camera2取代Camera),围绕一个物体360 ...
- C#图片采集软件 自动翻页 自动分类(收集美图必备工具)(一)
网站管理员希望将别人的整站数据下载到自己的网站里或者将别人网站的一些内容保存到自己的服务器上.从内容中抽取相关的字段,发布到自己的网站系统中.有时需要将网页相关的文件也保存到本地,如图片.附件等. 图 ...
- JAVA多线程超时加载当网页图片
先上图: 这一次没有采取正则匹配,而采取了最简单的java分割和替代方法进行筛选图片 它能够筛选如下的图片并保存到指定的文件夹 如: “http://xxxx/xxxx/xxx.jpg” 'http: ...
- Python爬虫 网页图片
一 概述 参考http://www.cnblogs.com/abelsu/p/4540711.html 弄了个Python捉取单一网页的图片,但是Python已经升到3+版本了.参考的已经失效,基本用 ...
- 14种网页图片和文字特效的jQuery插件代码
1.网页图片3d旋转jQuery代码 演示和下载地址 2.存css3实现的tabl选项卡代码 演示和下载地址 3.jQuery标签旋转代码 演示和下载地址 4.鼠标悬浮的图片选项卡代码 演示和下载地址 ...
- PHP抓取网页图片
<?php set_time_limit(0);//抓取不受时间限制 if($_POST['Submit']=="开始抓取"){ $URL=$_POST['link']; g ...
- python requests库爬取网页小实例:爬取网页图片
爬取网页图片: #网络图片爬取 import requests import os root="C://Users//Lenovo//Desktop//" #以原文件名作为保存的文 ...
- Python爬虫之网页图片抓取
一.引入 这段时间一直在学习Python的东西,以前就听说Python爬虫多厉害,正好现在学到这里,跟着小甲鱼的Python视频写了一个爬虫程序,能实现简单的网页图片下载. 二.代码 __author ...
- css sprite---css精灵网页图片应用处理方式分析
CSSSprites,在前端图片处理中经常用到的一种高效方法,下面参考百度百科的总结,非常到位,学习一下吧! CSSSprites在国内很多人叫css精灵,是一种网页图片应用处理方式.它允许你将一个页 ...
随机推荐
- HihoCoder 1236 Scores - bitset - 分块
Kyle is a student of Programming Monkey Elementary School. Just as others, he is deeply concerned wi ...
- ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 45, found 42. Created with MySQL 50560, now running 50725. Please use mysql_upgrade to fix this error.
centos7.5 登入mysql,进行授权报错 问题: mysql> grant all privileges on *.* to 'lvhanzhi'@'%' identified by ' ...
- Maven本地仓库引入自定义/第三方的jar
在cmd下输入如下: mvn install:install-file -Dfile=D:\ojdbc7.jar -DgroupId=com.tech4j.driver -DartifactId=or ...
- Flutter 第一次运行就出现白屏的问题
--enable-software-rendering 解决办法: 顶部菜单找到 run-->Edit Configurations 中加这么一句:
- 小C的数学问题 【单调栈】
问题 J: 小C的数学问题 时间限制: 1 Sec 内存限制: 128 MB 提交: 565 解决: 141 [提交] [状态] [命题人:外部导入] 题目描述 小C是个云南中医学院的大一新生,在 ...
- POJ 1679 The Unique MST 【判断最小生成树是否唯一】
Description Given a connected undirected graph, tell if its minimum spanning tree is unique. Defini ...
- ps一些疑问知识点
PS 的核心, 是 选择, 是 抠图, 不管是蒙版, 通道也好等等, 其实主要的作用还是 抠图. 还是精确地 选出你要处理的 内容对象! 如何改变工具预设? 使用工具预设, 可以将你当前正在使用的 / ...
- SpringBoot cookie工具类
code: import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annot ...
- Python, pandas: how to sort dataframe by index// Merge two dataframes by index
pd.concat([df1, df2], axis=1) df.sort_index(inplace=True) https://stackoverflow.com/questions/404680 ...
- oracle 之 创,增,删,改操作
--创建表 (包含其中的数据) create table TableName as select * from TableName --插入数据 insert into TableName(列,列.. ...