C# 网页图片爬虫的几种技术基础

简介:

一、文件流方式获取网络图片资源

方法1

复制代码
string url = string.Format(@"http://webservice.36wu.com/DimensionalCodeService.asmx/GetCodeImgByString?size={0}&content={1}", 5, 123456);
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(200, 200);
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, 0, 0, 210, 210, 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,4);

                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[1024];
                    int current = 0;
                    while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, 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 > 0)
            {
                return nodes[0].ChildNodes[0].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;  
    }  
复制代码

下载网站图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <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上的方法

2. 根据网址把图片下载到服务器C#代码

3. C#获取网页的HTML码、下载网站图片

4. C#如何通过URL下载图片?

 

没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。


    本文转自wenglabs博客园博客,原文链接:http://www.cnblogs.com/arxive/p/5926259.html,如需转载请自行联系原作者




相关文章
|
11月前
|
人工智能 运维 算法
基于 C# 深度优先搜索算法的局域网集中管理软件技术剖析
现代化办公环境中,局域网集中管理软件是保障企业网络高效运行、实现资源合理分配以及强化信息安全管控的核心工具。此类软件需应对复杂的网络拓扑结构、海量的设备信息及多样化的用户操作,而数据结构与算法正是支撑其强大功能的基石。本文将深入剖析深度优先搜索(Depth-First Search,DFS)算法,并结合 C# 语言特性,详细阐述其在局域网集中管理软件中的应用与实现。
242 3
|
12月前
|
数据采集 存储 机器学习/深度学习
Fuel 爬虫:Scala 中的图片数据采集与分析
Fuel 爬虫:Scala 中的图片数据采集与分析
|
10月前
|
数据采集 Web App开发 JavaScript
基于Selenium的Python爬虫抓取动态App图片
基于Selenium的Python爬虫抓取动态App图片
741 68
|
9月前
|
数据采集 Web App开发 JavaScript
Python爬虫解析动态网页:从渲染到数据提取
Python爬虫解析动态网页:从渲染到数据提取
|
10月前
|
数据采集 存储 前端开发
Python爬虫自动化:批量抓取网页中的A链接
Python爬虫自动化:批量抓取网页中的A链接
|
10月前
|
数据采集 Web App开发 JavaScript
Python爬虫如何获取JavaScript动态渲染后的网页内容?
Python爬虫如何获取JavaScript动态渲染后的网页内容?
|
缓存 监控 算法
基于 C# 网络套接字算法的局域网实时监控技术探究
在数字化办公与网络安全需求增长的背景下,局域网实时监控成为企业管理和安全防护的关键。本文介绍C#网络套接字算法在局域网实时监控中的应用,涵盖套接字创建、绑定监听、连接建立和数据传输等操作,并通过代码示例展示其实现方式。服务端和客户端通过套接字进行屏幕截图等数据的实时传输,保障网络稳定与信息安全。同时,文章探讨了算法的优缺点及优化方向,如异步编程、数据压缩与缓存、错误处理与重传机制,以提升系统性能。
288 2
|
数据采集 人工智能 监控
Crawl4LLM:你的模型还在吃垃圾数据?CMU博士开源AI爬虫,自动筛选高价值网页,数据抓取质量飙升300%
Crawl4LLM 是清华大学和卡内基梅隆大学联合开发的智能爬虫系统,通过网页价值评估和优先级队列技术,显著提升大语言模型预训练数据采集效率。
646 4
|
11月前
|
SQL 小程序 API
如何运用C#.NET技术快速开发一套掌上医院系统?
本方案基于C#.NET技术快速构建掌上医院系统,结合模块化开发理念与医院信息化需求。核心功能涵盖用户端的预约挂号、在线问诊、报告查询等,以及管理端的排班管理和数据统计。采用.NET Core Web API与uni-app实现前后端分离,支持跨平台小程序开发。数据库选用SQL Server 2012,并通过读写分离与索引优化提升性能。部署方案包括Windows Server与负载均衡设计,确保高可用性。同时针对API差异、数据库老化及高并发等问题制定应对措施,保障系统稳定运行。推荐使用Postman、Redgate等工具辅助开发,提升效率与质量。
450 0
|
Web App开发 Linux C#
C# 网页截图全攻略:三种技术与 Chrome 路径查找指南
本文主要介绍了在 C# 中实现网页截图的几种技术及相关要点。涵盖了 PuppeteerSharp、Selenium 和 HtmlToImage 三种方式,分别阐述了它们的安装步骤及核心代码。同时,针对在 C# 中寻找 Windows 上 chrome.exe 路径这一问题,分析了未安装 Google Chrome 和已安装两种情况下的查找原因,并给出了相关参考链接,还列举了一系列与 C# 使用 Selenium、获取 chrome.exe 路径以及在 Linux 上部署相关的参考资料。
497 11