C# 抓取网页的img src带参数的图片链接,并下载

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;
using System.Windows.Forms;

namespace ImageCollection
{
    public partial class Form1 : Form
    {
        private static string Path = AppDomain.CurrentDomain.BaseDirectory + "img";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnshuaqu_Click(object sender, EventArgs e)
        {
            string url = txturl.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("请输入URl");
                return;
            }
            txtimg.AppendText("开始抓取中:\r\n");
            Thread th = new Thread(() => ShuaQu(url)) { IsBackground = true };
            th.Start();
        }

        private void ShuaQu(string url)
        {
            DirectoryInfo di = new DirectoryInfo(Path);
            if (System.IO.Directory.Exists(Path))
            {
                di.Delete(true);
            }
            System.IO.Directory.CreateDirectory(Path);
            string result = WebHttp.HttpGet(url, null, 3);
            string[] str = GetHtmlImageUrlList(result);
            txtimg.Invoke(new Action(() =>
            {
                txtimg.AppendText("已经获取到数据!"+str.Count() + "\r\n");
            }));
            //建立获取网页标题正则表达式
            String regex = @"<title>.+</title>";

            //返回网页标题
            String title = Regex.Match(result, regex).ToString();
            txttitle.Invoke(new Action(() => {
                txttitle.Text = Regex.Replace(title, @"[\""]+", "");
            }));
            foreach (string s in str)
            {
                Uri u = new Uri(s);
                if (u.Host == "www.xxx.com")
                {
                    Thread downimg = new Thread(() => Get_img(s)) { IsBackground = true };
                    downimg.Start();
                    txtimg.Invoke(new Action(() => {
                        txtimg.AppendText(s + "\r\n");
                    }));
                }
            }
            txtimg.Invoke(new Action(() =>
            {
                txtimg.AppendText("全部抓取完成!\r\n");
            }));
        }

        public void Get_img(string imgpath)
        {

            string[] file = imgpath.Split(‘?‘);
            string name = System.IO.Path.GetFileName(file[0]);
            WebClient mywebclient = new WebClient();
            mywebclient.DownloadFile(imgpath, Path + @"\" + name);
            //Bitmap img = null;
            //HttpWebRequest req;
            //HttpWebResponse res = null;
            //try
            //{
            //    System.Uri httpUrl = new System.Uri(imgpath);
            //    req = (HttpWebRequest)(WebRequest.Create(httpUrl));
            //    req.Timeout = 180000; //设置超时值10秒
            //    req.UserAgent = "XXXXX";
            //    req.Accept = "XXXXXX";
            //    req.Method = "GET";
            //    res = (HttpWebResponse)(req.GetResponse());
            //    img = new Bitmap(res.GetResponseStream());//获取图片流
            //    img.Save(Path + @"\"+name);//随机名
            //}

            //catch (Exception ex)
            //{
            //    string aa = ex.Message;
            //}
            //finally
            //{
            //    res.Close();
            //}
        }

        /// <summary>
        /// 取得HTML中所有图片的 URL。
        /// </summary>
        /// <param name="sHtmlText">HTML代码</param>
        /// <returns>图片的URL列表</returns>
        private string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""‘]?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""‘<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }
    }
}
#region 下载图片到Image
public static Image UrlToImage(string url) {
    WebClient mywebclient = new WebClient();
    byte[] Bytes = mywebclient.DownloadData(url);
    using (MemoryStream ms = new MemoryStream(Bytes)) {
        Image outputImg = Image.FromStream(ms);
        return outputImg;
    }
}
#endregion
时间: 2024-08-24 17:49:07

C# 抓取网页的img src带参数的图片链接,并下载的相关文章

正则抓取网页所有href和src

根据抓取的页面,用正则来匹配页面href和src string UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:29.0) Gecko/20100101 Firefox/29.0"; string ContentType = ""; Uri strReqUrl = new Uri("http://m.lhrb.ufstone.net/"); protected void Application_Begin

使用wget工具抓取网页和图片 成功尝试

使用wget工具抓取网页和图片 发表于1年前(2014-12-17 11:29)   阅读(2471) | 评论(14) 85人收藏此文章, 我要收藏 赞7 wget 网页抓取 图片抓取 目录[-] 奇怪的需求 wget概述 wget尝试 wget正解 奇怪的需求 公司需要将服务器的网页缓存到路由器,用户在访问该网页时就直接取路由器上的缓存即可.虽然我不知道这个需求有什么意义,但还是尽力去实现吧. wget概述 wget是unix和类unix下的一个网页抓取工具,待我熟悉它后,发现它的功能远不止

file_get_contents抓取网页乱码的解决

有时候用 file_get_contents() 函数抓取网页会发生乱码现象.有两个原因会导致乱码,一个是编码问题,一个是目标页面开了Gzip. 编码问题好办,把抓取到的内容转下编码即可($content=iconv("GBK", "UTF-8//IGNORE", $content);),我们这里讨论的是如何抓取开了Gzip的页面.怎么判断呢?获取的头部当中有Content-Encoding: gzip说明内容是GZIP压缩的.用FireBug看一下就知道页面开了g

java 抓取网页图片

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

【iOS】正则表达式抓取网页数据制作小词典

应用程序不一定要自己去提供数据,有现成的数据学会去用才好. 网络很大,各种搜索引擎每天到处爬.本文通过正则表达式抓取网站的数据来做一个小词典. 一.正则表达式的使用 1. 确定匹配方案,即pattern 2. 用pattern实例化NSRegularExpression 3. 用匹配方法开始匹配. 匹配一次:可以使用firstMatch方法 匹配多次:可以用matchs方法 正则表达式对照表:(在网上找到了一个很不错的表,正则表达式各个语言通用) http://www.jb51.net/shou

Python -- 网络编程 -- 抓取网页图片 -- 图虫网

字符串(str)编码成字节码(bytes),字节码解码为字符串 获取当前环境编码:sys.stdin.encoding url编码urllib.parse.quote() url解码urllib.parse.unquote() 列表去重:pages = list(set(pages)) 创建文件夹(可多级创建):os.makedirs(folder)  os.mkdir()只能单级创建 首先分析网页(图虫网)的URL规律: 根网页地址形如: http://tuchong.com/tags/人像/

Python3简单爬虫抓取网页图片

现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2),所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到大家,并希望大家批评指正. 1 import urllib.request 2 import re 3 import os 4 import urllib 5 #根据给定的网址来获取网页详细信息,得到的html就是网页的源代码 6 def getHtml(url): 7 page = urllib.r

delphi 7中使用idhttp抓取网页 解决假死现象

在delphi 7中使用idhttp抓取网页,造成窗口无反应的假死状态.通过搜索获得两种方法. 1.写在线程中,但是调用比较麻烦 2.使用delphi 提供的idantifreeze(必须安装indy).在indy misc中将idfreeantifreeze放入程序中, 将OnlyWhenIdle状态修改为False即可.方便简单. ===================================== 直接采用Delphi自带Control控件INDY组件为例.新建个工程,放上个TIdH

PowerShell 抓取网页表格

今天无意中看到了传教士写的一篇博文http://www.cnblogs.com/piapia/p/5367556.html(PowerShell中的两只爬虫),很受启发,自己试着抓了一下,成功地抓取了网页的表格.因为我是英文版的系统,中文系统的界面转换成字符串都成了乱码,因此测试都是在英文网页上操作的. PowerShell 5里面有一个新的函数叫做ConvertFrom-String, 他的作用是把字符串转换成对象.其中一个参数是可以根据指定的模板,把对应的那一部分字符串匹配出来生成对象,我们