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, );
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[]);
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 = ;
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
C# 抓取网页的img src带参数的图片链接,并下载的更多相关文章
- 使用wget工具抓取网页和图片 成功尝试
使用wget工具抓取网页和图片 发表于1年前(2014-12-17 11:29) 阅读(2471) | 评论(14) 85人收藏此文章, 我要收藏 赞7 wget 网页抓取 图片抓取 目录[-] ...
- 使用wget工具抓取网页和图片 及 相关工具几个
想保存一些网页,最后找到这 wget 的 shell脚本,虽然不是太理想,亲测可用呢. 使用wget工具抓取网页和图片 来源 https://my.oschina.net/freestyletim ...
- Java 抓取网页中的内容【持续更新】
背景:前几天复习Java的时候看到URL类,当时就想写个小程序试试,迫于考试没有动手,今天写了下,感觉还不错 内容1. 抓取网页中的URL 知识点:Java URL+ 正则表达式 import jav ...
- C语言调用curl库抓取网页图片
思路是先用curl抓取网页源码,然后以关键字寻找出图片网址. #include <stdio.h> #include <stdlib.h> #include <str ...
- C语言调用curl库抓取网页图片(转)
思路是先用curl抓取网页源码,然后以关键字寻找出图片网址. 范例: #include <stdio.h> #include <stdlib.h> #include < ...
- python分布式抓取网页
呵呵,前两节好像和python没多大关系..这节完全是贴代码, 这是我第一次写python,很多地方比较乱,主要就看看逻辑流程吧. 对于编码格式确实搞得我头大..取下来页面不知道是什么编码,所以先找c ...
- delphi 7中使用idhttp抓取网页 解决假死现象
在delphi 7中使用idhttp抓取网页,造成窗口无反应的假死状态.通过搜索获得两种方法. 1.写在线程中,但是调用比较麻烦 2.使用delphi 提供的idantifreeze(必须安装indy ...
- PHP抓取网页图片
<?php set_time_limit(0);//抓取不受时间限制 if($_POST['Submit']=="开始抓取"){ $URL=$_POST['link']; g ...
- HttpClient(一)HttpClient抓取网页基本信息
一.HttpClient简介 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包, 并且它支 ...
随机推荐
- c++ primer读书笔记之c++11(二)
1 新的STL模板类型,std::initializer_list<T> c++11添加了initializer_list模板类型,用于提供参数是同类型情况的可变长度的参数传递机制,头文件 ...
- Delphi实现RGB色环的代码绘制(XE10.2+WIN764)
相关资料: http://blog.csdn.net/tokimemo/article/details/18702689 http://www.myexception.cn/delphi/215402 ...
- Web基础 HTML CSS JS JQuery AJAX
1. Web基础 网页的骨骼HTML 什么是HTML超文本标记语言:Hyper Text Markup Language 这都不重要,重要的是:HTML是Web网页的基本组成部分HTML中定义的元素, ...
- java基础篇---Servlet过滤器
Servlet过滤器从字面上的字意理解为景观一层次的过滤处理才达到使用的要求,而其实Servlet过滤器就是服务器与客户端请求与响应的中间层组件,在实际项目开发中Servlet过滤器主要用于对浏览器的 ...
- quartz定时任务框架的使用以及原理
quartz定时任务时间设置 这些星号由左到右按顺序代表 : * * * * * * * ...
- PHP判断当前页面是电脑登录,还是手机登录
//判断是否是电脑登录,还是手机登录 public function isMobil() { $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_S ...
- 有用sql语句一
DECLARE @retval int, @param1 int EXECUTE @retval=master.dbo.xp_fileexist 'D:\TkSoft\SamplePic\Fabric ...
- WPF中自定义路由事件
public class MyButtonSimple: Button { // Create a custom routed event by first registering a RoutedE ...
- 使用Task代替ThreadPool和Thread
转载:改善C#程序的建议9:使用Task代替ThreadPool和Thread 一:Task的优势 ThreadPool相比Thread来说具备了很多优势,但是ThreadPool却又存在一些使用上的 ...
- Git做代码增量发布的重要用法 - --diff-filter
你以为有 bash git diff --name-only 就够了,NO! 对于PHP开发的系统来说,增量发布,一般只需部署新增的文件和有变动的文件,但很多时候,文件是删除的或重构成其它文件名或重构 ...