日期:2014-05-20  浏览次数:20721 次

获取网页中的图片
想获取网页中的图片文件下载到本地
现在已经使用weblient将网页文件下载到字符串中,
然后应该设置正则表达式,寻找匹配的链接,然后下载对不对,这里不会写了

------解决方案--------------------
帮LZ顶
------解决方案--------------------
学习!
------解决方案--------------------

------解决方案--------------------
有成熟方案的朋友能共享一下吗


不仅图片,包括css,js等
------解决方案--------------------
估计是路径不正确。
写在网页的一般是相对路径,如:\img\logon.jpg,你必须替换为 http:\\站点\img\logon.jpg。如果是..\..\img\logon.jpg,那你还需要从当前路径开始网上找2层目录,再接回去
------解决方案--------------------
我的想法是利用自带的MSHTML这个COM组件,项目里添加引用它就可以了。


HtmlElementCollection hec = web1.Document.GetElementsByTagName( "img ");

foreach (HtmlElement he in hec)
{
MessageBox.Show(he.GetAttribute( "src ").ToString());
}

web1 是WebBrowser控件。

------解决方案--------------------
private bool PicSaveAs(string urlstr)
{
Random rand = new Random();
string picPath = " ";
string[] pathstr = urlstr.Split(new char[]{ ', '});
string dtUnit = pathstr[0]; //时间单位
string picurl = pathstr[1]; //图片路径

bool isSave = true;
try
{
StBar.Text = "保存图片.... ";
string body;
http.open( "GET ",picurl,false, " ", " ");
http.send( " ");
body =http.responseText.Replace( "\n ",null).Replace( "\r ",null).ToLower();
body = body.Substring(body.IndexOf( "src=\ "http://211.147.16.21:80/songliao/shortterm/ "),150);
body = body.Substring(0,body.LastIndexOf( ".jpg ") + 4);
body = body.Replace( "src=\ " ",null).Replace( "shortterm ", "shortTerm ");
http.open( "GET ",body,false, " ", " ");
http.send( " ");
picPath = body.Substring(body.LastIndexOf( ". "));
//picPath = DateTime.Now.ToString( "yyyyMMdd ") + rand.Next(1000,9999) + picPath;
picPath = GetPicName(this.TxtPicSavePath.Text,dtUnit) + picPath;
picPath = this.TxtPicSavePath.Text + picPath;
byte[] picbyte = (byte[])http.responseBody;
System.IO.FileStream savepic = new System.IO.FileStream(@picPath,System.IO.FileMode.Create);
savepic.Write(picbyte,0,picbyte.Length);
savepic.Close();
savepic = null;
body = null;
isSave = true;
}
catch
{
isSave=false;
//MessageBox.Show(ex.Message);
}
return isSave;
}

思想:
1、找到图片地址,读取图片二进制代码(用MSXML2.XMLHTTP() 或 System.Net.WebClient 都可以)
2、把二进制代码保存成图片文件。