C#經由過程正則表達式完成提取網頁中的圖片。本站提示廣大學習愛好者:(C#經由過程正則表達式完成提取網頁中的圖片)文章只能為提供參考,不一定能成為您想要的結果。以下是C#經由過程正則表達式完成提取網頁中的圖片正文
今朝在做項目中有處置圖片的部門,參考了一下網上案例,本身寫了一個獲得內容中的圖片地址的辦法。
普通來講一個 HTML 文檔有許多標簽,好比“<html>”、“<body>”、“<table>”等,想把文檔中的 img 標簽提掏出來其實不是一件輕易的事。因為 img 標簽款式變更多端,使提取的時刻用法式尋覓其實不輕易。因而想要尋覓它們就必需寫一個異常健全的正則表達式,否則有能夠會找得不全,或許找出來的不是准確的 img 標簽。
我們可以從 HTML 標簽的格局去想應當怎樣建這個正則表達式。起首要想一下 img 標簽有幾種寫法,疏忽年夜小寫不看的話,上面列出 img 標簽能夠湧現的幾種情形。
<img> <img/> <img src=/>
這一些標簽不消斟酌,由於沒有圖片資本地址。
<img src = /images/pic.jpg/ > <img src =" /images/pic.jpg" > <img src= '/images/pic.jpg ' / >
這一些標簽都有圖片資本地址,別的還有一個特色就是有引號對,能夠為單引號,也能夠為雙引號。由於不須要同時婚配引號對,所以正則表達式可以這麼寫:@"<img\s*src\s*=\s*[""']?\s*(?[^\s""'<>]*)\s*/?\s*>"
<img width="320" height="240" src=/images/pic.jpg onclick="window.open('/images/pic.jpg')">
由於 img 和 src 之間能夠會有其他的參數,所以“<img”要有個單詞停止,好比說不克不及是“<imgabc”,異樣 src 後面也是一樣,應用單詞停止符“\b”有一個利益就是省去了表現空格的“\s*”。別的因為 img 標簽中弗成以湧現“<”、“>”如許的符號,所以要改寫後面的正則表達式:@"<img\b[^<>]*?\bsrc\s*=\s*[""']?\s*(?<imgUrl>[^\s""'<>]*)[^<>]*?/?\s*>"
<img width="320" height="240" src = "
/images/pic.jpg" />
像這類能夠會用回車符折行的成績有時刻會湧現,所以在有空格離開的處所要包括回車換行和 TAB 字符,別的在圖片地址中不克不及湧現空格、TAB、回車和換行字符。
所以下面的正則表達式可以改成:@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>"
上面寫出獲得HTML中一切圖片地址的類HvtHtmlImage:
using System.Text.RegularExpressions;
namespace HoverTree.HoverTreeFrame.HvtImage
{
public class HvtHtmlImage
{
/// <summary>
/// 獲得HTML中一切圖片的 URL。
/// </summary>
/// <param name="sHtmlText">HTML代碼</param>
/// <returns>圖片的URL列表</returns>
public static string[] GetHvtImgUrls(string sHtmlText)
{
// 界說正則表達式用來婚配 img 標簽
Regex m_hvtRegImg = 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 = m_hvtRegImg.Matches(sHtmlText);
int m_i = 0;
string[] sUrlList = new string[matches.Count];
// 獲得婚配項列表
foreach (Match match in matches)
sUrlList[m_i++] = match.Groups["imgUrl"].Value;
return sUrlList;
}
}
}
上面我們再來看一個例子
public Array MatchHtml(string html,string com)
{
List<string> urls = new List<string>();
html = html.ToLower();
//獲得SRC標簽中的URL
Regex regexSrc = new Regex("src=\"[^\"]*[(.jpg)(.png)(.gif)(.bmp)(.ico)]\"");
foreach(Match m in regexSrc.Matches(html))
{
string src = m.Value;
src = src.WordStr("src=","").WordStr("\"","");
if (!src.Contains("http"))
src = com + src;
if(!urls.Contains(src))
urls.Add(src);
}
//獲得HREF標簽中URL
Regex regexHref = new Regex("href=\"[^\"]*[(.jpg)(.png)(.gif)(.bmp)(.ico)]\"");
foreach (Match m in regexHref.Matches(html))
{
string href = m.Value;
href = href.WordStr("href=", "").WordStr("\"", "");
if (!href.Contains("http"))
href = com + href;
if(!urls.Contains(href))
urls.Add(href);
}
return urls.ToArray();
}
[DllImport("kernel32.dll")]
static extern bool SetConsoleMode(IntPtr hConsoleHandle, int mode);
[DllImport("kernel32.dll")]
static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int mode);
[DllImport("kernel32.dll")]
static extern IntPtr GetStdHandle(int handle);
const int STD_INPUT_HANDLE = -10;
const int ENABLE_QUICK_EDIT_MODE = 0x40 | 0x80;
public static void EnableQuickEditMode()
{
int mode; IntPtr handle = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(handle, out mode);
mode |= ENABLE_QUICK_EDIT_MODE;
SetConsoleMode(handle, mode);
}
static void Main(string[] args)
{
EnableQuickEditMode();
int oldCount = 0;
Console.Title = "TakeImageFromInternet";
string path = "E:\\Download\\loading\\";
while (true)
{
Console.Clear();
string countFile = "E:\\CountFile.txt";//用來計數的文本,以致於文件名不反復
int cursor = 0;
if (File.Exists(countFile))
{
string text = File.ReadAllText(countFile);
try
{
cursor =oldCount = Convert.ToInt32(text);//次數多了建議應用long
}
catch { }
}
Console.Write("please input a url:");
string url = "http://www.百度.com/";
string temp = Console.ReadLine();
if (!string.IsNullOrEmpty(temp))
url = temp;
Match mcom = new Regex(@"^(?i)http://(\w+\.){2,3}(com(\.cn)?|cn|net)\b").Match(url);//獲得域名
string com = mcom.Value;
//Console.WriteLine(mcom.Value);
Console.Write("please input a save path:");
temp = Console.ReadLine();
if (Directory.Exists(temp))
path = temp;
Console.WriteLine();
WebClient client = new WebClient();
byte[] htmlData = null;
htmlData = client.DownloadData(url);
MemoryStream mstream = new MemoryStream(htmlData);
string html = "";
using (StreamReader sr = new StreamReader(mstream))
{
html = sr.ReadToEnd();
}
Array urls = new MatchHtmlImageUrl().MatchHtml(html,com);
foreach (string imageurl in urls)
{
Console.WriteLine(imageurl);
byte[] imageData = null;
try
{
imageData = client.DownloadData(imageurl);
}
catch { }
if (imageData != null && imageData.Length>0)
using (MemoryStream ms = new MemoryStream(imageData))
{
try
{
string ext = Aping.Utility.File.FileOpration.ExtendName(imageurl);
ImageFormat format = ImageFormat.Jpeg;
switch (ext)
{
case ".jpg":
format = ImageFormat.Jpeg;
break;
case ".bmp":
format = ImageFormat.Bmp;
break;
case ".png":
format = ImageFormat.Png;
break;
case ".gif":
format = ImageFormat.Gif;
break;
case ".ico":
format = ImageFormat.Icon;
break;
default:
continue;
}
Image image = new Bitmap(ms);
if (Directory.Exists(path))
image.Save(path + "\\" + cursor + ext, format);
}
catch(Exception ex) { Console.WriteLine(ex.Message); }
}
cursor++;
}
mstream.Close();
File.WriteAllText(countFile, cursor.ToString(), Encoding.UTF8);
Console.WriteLine("take done...image count:"+(cursor-oldCount).ToString());
}
}