2012-01-31 24 views
11

不使用API​​?如何從mshtml.htmlimg獲取圖像到硬盤

我知道有幾種方法。

我正在使用mshtml庫,這比webbrowser控件更好。我正在有效地自動化Internet Explorer。

基本上我更喜歡一種直接拍攝圖像的方式,而不必知道htmlimg的URL並下載它。

我知道我可以從圖像元素中獲取網址,並通過webclient下載。 圖像根據Cookie和IP而變化。那就不會呢。

我希望htmlimg元素顯示的確切圖像是存儲的圖像。

基本上就好像有人正在屏幕上顯示的內容一樣。

回答

1

有此這裏的老辦法:

http://p2p.wrox.com/c/42780-mshtml-how-get-images.html#post169674

這些天雖然你可能想看看在HTML敏捷性包:

http://htmlagilitypack.codeplex.com/

的文檔是不完全然而偉大的;所以這段代碼可能會有所幫助:

HtmlDocument htmlDoc = new HtmlDocument(); 
htmlDoc.LoadHtml(html); 

// You can also load a web page by utilising WebClient and loading in the stream - use one of the htmlDoc.Load() overloads 

var body = htmlDoc.DocumentNode.Descendants("body").FirstOrDefault(); 

foreach (var img in body.Descendants("img")) 
{ 
    var fileUrl = img.Attributes["src"].Value; 
    var localFile = @"c:\localpath\tofile.jpg"; 

    // Download the image using WebClient: 
    using (WebClient client = new WebClient()) 
    { 
     client.DownloadFile("fileUrl", localFile); 
    } 
} 
+0

該解決方案計入瞭解URL並直接下載。該圖像不僅取決於URL,還取決於Cookie和代理信息。我可以將代理和cookie信息模仿到webclient,但這很複雜。 – 2015-10-20 04:25:23