C# 网页图片爬虫的几种技术基础
一、文件流方式获取网络图片资源
方法1
string url = string.Format(@"http://webservice.36wu.com/DimensionalCodeService.asmx/GetCodeImgByString?size={0}&content={1}", , );
System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
System.Net.WebResponse webres = webreq.GetResponse();
using(System.IO.Stream stream = webres.GetResponseStream())
{
ictureBox1.Image = Image.FromStream(stream);
}
方法2
生成图片的URL假设是这样:http://localhost/administrator/qrcode.aspx?pid=78
qrcode.aspx.cs的生成图片的部分代码:
Image image = new Bitmap(, );
Graphics g = Graphics.FromImage(image);
try
{
string url="http://localhost"; DotNetBarcode bc = new DotNetBarcode();
bc.Type = DotNetBarcode.Types.QRCode;
bc.PrintCheckDigitChar = true;
bc.WriteBar(url, , , , , g); System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.ClearContent();
//Response.ContentType = "image/Png";
//Response.BinaryWrite(ms.ToArray());
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("qrcode.png", System.Text.Encoding.UTF8));
Response.BinaryWrite(ms.ToArray());
ms.Dispose();
}
finally
{
g.Dispose();
image.Dispose();
}
或者这样
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 //以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
二、WebClient方式从服务器上下载文件
参考方法1:
/// <summary>
/// 下载服务器文件至客户端
/// </summary>
/// <param name="url">被下载的文件地址,绝对路径</param>
/// <param name="dir">另存放的目录</param>
public void DownloadUrlFile(string url, string dir)
{
WebClient client = new WebClient();
string fileName = Path.GetFileName(url); //被下载的文件名
string path = dir + fileName; //另存为的绝对路径+文件名
try
{
if (!System.IO.Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
}
if (!System.IO.File.Exists(path))
{
client.DownloadFile(url, path);
}
}
catch (Exception)
{
// ShowError("文件下载失败!");
}
}
参考方法2 [2]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetPictureByUrl.aspx.cs" Inherits="HoverTreeMobile.GetPictureByUrl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>根据网址把图片下载到服务器 - 何问起</title>
</head>
<body>
<form id="form1" runat="server">
<div>
图片网址:<br /><asp:TextBox runat="server" ID="textBoxImgUrl" Width="500" Text="http://hovertree.com/hvtimg/201508/cnvkv745.jpg" />
<br /> <asp:Button runat="server" ID="btnImg" Text="下载" OnClick="btnImg_Click" />
<br /><asp:Image runat="server" ID="hvtImg" />
<br />
<asp:Literal runat="server" ID="ltlTips" />
</div>
</form>
</body>
</html>
页面所对应的代码
using System; namespace HoverTreeMobile
{
public partial class GetPictureByUrl : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void btnImg_Click(object sender, EventArgs e)
{
try
{
System.Net.WebClient m_hvtWebClient = new System.Net.WebClient(); //如果不是指定格式图片
//例如http://hovertree.com/hvtart/bjae/t2lo8pf7.htm 是htm文件,不是图片
if (!(textBoxImgUrl.Text.EndsWith(".jpg")
|| textBoxImgUrl.Text.EndsWith(".gif")
|| textBoxImgUrl.Text.EndsWith(".png")))
{
ltlTips.Text = "输入的不是指定格式的图片的网址"; return;
} //生成随机的图片文件名
string m_picFileName = HoverTree.HoverTreeFrame.Utils.GetHoverTreeString()+ HoverTree.HoverTreeFrame.HoverString.GetLastStr(textBoxImgUrl.Text,); string m_keleyiPicture = Server.MapPath("/hovertreeimages/"+ m_picFileName);
//根据网址下载文件
m_hvtWebClient.DownloadFile(textBoxImgUrl.Text, m_keleyiPicture); hvtImg.ImageUrl = "/hovertreeimages/" + m_picFileName;
ltlTips.Text = string.Empty;
}
catch(Exception ex)
{
ltlTips.Text = ex.ToString();
}
}
}
}
//生成随机的图片文件名
string m_picFileName = HoverTree.HoverTreeFrame.Utils.GetHoverTreeString()+ HoverTree.HoverTreeFrame.HoverString.GetLastStr(textBoxImgUrl.Text,4);
以上代码,请下载源代码查看详细实现方法。部分可到 LINK 查看。
HoverTree 开源项目:新增根据网址把图片下载到服务器功能
请看 HoverTreeMobile 项目,http://hovertree.com,何问起,源代码下载 LINK。
三、网页相关的方式
方法1:
public partial class DownLoadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string picName = Request.QueryString["InternalSysURL"];
if (!String.IsNullOrEmpty(picName))
{
byte[] content = this.GetImageContent(picName);
this.WriteResponse(picName, content);
}
} #region
private byte[] GetImageContent(string picName)
{
string fileURL = GetImgUrlPrefix() + picName; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileURL);
request.AllowAutoRedirect = true; WebProxy proxy = new WebProxy();
proxy.BypassProxyOnLocal = true;
proxy.UseDefaultCredentials = true; request.Proxy = proxy; WebResponse response = request.GetResponse(); using (Stream stream = response.GetResponseStream())
{
using (MemoryStream ms = new MemoryStream())
{
Byte[] buffer = new Byte[];
int current = ;
while ((current = stream.Read(buffer, , buffer.Length)) != )
{
ms.Write(buffer, , current);
}
return ms.ToArray();
}
}
} private void WriteResponse(string picName, byte[] content)
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(picName, Encoding.Default));
Response.AppendHeader("Content-Length", content.Length.ToString());
Response.BinaryWrite(content);
Response.Flush();
Response.End();
} private static string GetImgUrlPrefix()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "//Pages//ItemMaintain//ImageDownLoad.xml");
XmlNodeList nodes = xmlDoc.GetElementsByTagName("ProductImageOriginal");
if (nodes.Count > )
{
return nodes[].ChildNodes[].Value;
}
else { return ""; }
} #endregion
}
方法2[3]:
根据URL请求获取页面HTML代码
/// <summary>
/// 获取网页的HTML码
/// </summary>
/// <param name="url">链接地址</param>
/// <param name="encoding">编码类型</param>
/// <returns></returns>
public static string GetHtmlStr(string url, string encoding)
{
string htmlStr = "";
if (!String.IsNullOrEmpty(url))
{
WebRequest request = WebRequest.Create(url); //实例化WebRequest对象
WebResponse response = request.GetResponse(); //创建WebResponse对象
Stream datastream = response.GetResponseStream(); //创建流对象
Encoding ec = Encoding.Default;
if (encoding == "UTF8")
{
ec = Encoding.UTF8;
}
else if (encoding == "Default")
{
ec = Encoding.Default;
}
StreamReader reader = new StreamReader(datastream, ec);
htmlStr = reader.ReadToEnd(); //读取数据
reader.Close();
datastream.Close();
response.Close();
}
return htmlStr;
}
下载网站图片
/// <summary>
/// 下载网站图片
/// </summary>
/// <param name="picUrl"></param>
/// <returns></returns>
public string SaveAsWebImg(string picUrl)
{
string result = "";
string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/File/"; //目录
try
{
if (!String.IsNullOrEmpty(picUrl))
{
Random rd = new Random();
DateTime nowTime = DateTime.Now;
string fileName = nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + ".jpeg";
WebClient webClient = new WebClient();
webClient.DownloadFile(picUrl, path + fileName);
result = fileName;
}
}
catch { }
return result;
}
参考文章
1. C# 通过URL获取图片并显示在PictureBox上的方法
C# 网页图片爬虫的几种技术基础的更多相关文章
- Jmeter(四十六) - 从入门到精通高级篇 - Jmeter之网页图片爬虫-下篇(详解教程)
1.简介 上一篇介绍了爬取文章,这一篇宏哥就简单的介绍一下,如何爬取图片然后保存到本地电脑中.网上很多漂亮的壁纸或者是美女.妹子,想自己收藏一些,挨个保存太费时间,那你可以利用爬虫然后批量下载. 2. ...
- node爬虫 -- 网页图片
相信大家都听说过爬虫,我们也听说过Python是可以很方便地爬取网络上的图片,但是奈何本人不会Python,就只有通过 Node 来实践一下了. 接下来看我如何 板砖 ! !!
- Jmeter(四十一)_图片爬虫
今天教大家用元件组合,做一个网页图片爬虫. 需要用到的元件:循环控制器+计数器+xpath提前器+函数嵌套+beanshell代码 首先我们确定一下要爬取的图片网站:https://dp.pconli ...
- python写的百度图片爬虫
学了一下python正则表达式,写一个百度图片爬虫玩玩. 当技术遇上心术不正的人,就成我这样的2B青年了. python3.6开发.程序已经打包好,下载地址: http://pan.baidu.com ...
- Python多线程爬虫爬取网页图片
临近期末考试,但是根本不想复习!啊啊啊啊啊啊啊!!!! 于是做了一个爬虫,网址为 https://yande.re,网页图片为动漫美图(图片带点颜色........宅男福利 github项目地址为:h ...
- Python爬虫之网页图片抓取
一.引入 这段时间一直在学习Python的东西,以前就听说Python爬虫多厉害,正好现在学到这里,跟着小甲鱼的Python视频写了一个爬虫程序,能实现简单的网页图片下载. 二.代码 __author ...
- Python3简单爬虫抓取网页图片
现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2), 所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到 ...
- node:爬虫爬取网页图片
代码地址如下:http://www.demodashi.com/demo/13845.html 前言 周末自己在家闲着没事,刷着微信,玩着手机,发现自己的微信头像该换了,就去网上找了一下头像,看着图片 ...
- Python学习--两种方法爬取网页图片(requests/urllib)
实际上,简单的图片爬虫就三个步骤: 获取网页代码 使用正则表达式,寻找图片链接 下载图片链接资源到电脑 下面以博客园为例子,不同的网站可能需要更改正则表达式形式. requests版本: import ...
随机推荐
- PostgreSQL+PostGIS的使用 函数清单
一. PostgreSQL与PostGIS的关系 PostgreSQL 是世界上技术最先进的开源数据库,其前身是1977年一个源于Berkeley名为Ingres的非关系型数据库,其项目领导人为Mic ...
- Spring Aop实例之xml配置
AOP的配置方式有2种方式:xml配置和AspectJ注解方式.今天我们就来实践一下xml配置方式. 我采用的jdk代理,所以首先将接口和实现类代码附上 package com.tgb.aop; pu ...
- MBProgressHUD ---
1,MBProgressHUD常用属性和用法Demo - (void)testMBProgressHUD { NSLog(@"test MBProgressHUD "); /* 要 ...
- 【递推】BZOJ 3930: [CQOI2015]选数
Description 我们知道,从区间[L,H](L和H为整数)中选取N个整数,总共有(H-L+1)^N种方案.小z很好奇这样选出的数的最大公约数的规律,他决定对每种方案选出的N个整数都求一次最大公 ...
- BZOJ 1710: [Usaco2007 Open]Cheappal 廉价回文
Description 为了跟踪所有的牛,农夫JOHN在农场上装了一套自动系统. 他给了每一个头牛一个电子牌号 当牛走过这个系统时,牛的名字将被自动读入. 每一头牛的电子名字是一个长度为M (1 &l ...
- 无法为请求的 Configuration 对象创建配置文件 错误原因
Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 无法为请求的 Configura ...
- FaceNet--Google的人脸识别(转)
引入 随着深度学习的出现,CV领域突破很多,甚至掀起了一股CV界的创业浪潮,当次风口浪尖之时,Google岂能缺席.特贡献出FaceNet再次刷新LFW上人脸验证的效果记录. 本文是阅读FaceNet ...
- <span> <div> 局部 keydown ,keyup事件。页面部分div $(document) 无效,可能焦点,添加焦点。
前天改一个bug, js 实现的一个 面板拖拉,左右各两个列表,中间面板画线连接,页面左侧列表选中后,key 事件无效.右侧选中确有效,很奇怪,查看源码,左侧选中后,$(document).on(&q ...
- CF135A Replacement
http://codeforces.com/problemset/problem/135/A 题意 : 我能说我卡在这个题的题意上很久吗.....这个题就是在数组里找一个数,然后找另一个数把他替换掉, ...
- Nginx的介绍和使用
http://blog.csdn.net/shimiso/article/details/8690897 1.什么是Nginx Nginx(发音同 engine x)是一款轻量级的Web 服务器/反向 ...