Как загрузить изображение с WEB страницы, не используя его URL адрес - VB

Узнай цену своей работы

Формулировка задачи:

Задача: есть адрес веб-страницы, на которой расположена картинка. Эта картинка при обновлении страницы меняется (скажем так - это каптча с постоянным URL-адресом). Как программно сохранить ее на диск? Для работы со страницей использую объект "InternetExplorer.Application"

Не по теме:

С Webbrowser какие-то проблемы. При проверке свойств .busy и .readystate

иногда

с вероятностью 50 % появляется ошибка "object does not support this property or method".

Я нашел класс для работы с кешем, но пока не разобрался, как ним пользоваться и умеет ли он "вытягивать" картинки.
Листинг программы
  1. Option Explicit
  2. Private Const LMEM_FIXED As Long = &H0
  3. Private Const LMEM_ZEROINIT As Long = &H40
  4. Private Type FILETIME
  5. lLowDateTime As Long
  6. lHighDateTime As Long
  7. End Type
  8. Private Type SYSTEMTIME
  9. wYear As Integer
  10. wMonth As Integer
  11. wDayOfWeek As Integer
  12. wDay As Integer
  13. wHour As Integer
  14. wMinute As Integer
  15. wSecond As Integer
  16. wMilliseconds As Integer
  17. End Type
  18. Private Type INTERNET_CACHE_ENTRY_INFO
  19. dwStructSize As Long
  20. lpszSourceUrlName As Long
  21. lpszLocalFileName As Long
  22. CacheEntryType As Long
  23. dwUseCount As Long
  24. dwHitRate As Long
  25. dwSizeLow As Long
  26. dwSizeHigh As Long
  27. LastModifiedTime As FILETIME
  28. ExpireTime As FILETIME
  29. LastAccessTime As FILETIME
  30. LastSyncTime As FILETIME
  31. lpHeaderInfo As Long
  32. dwHeaderInfoSize As Long
  33. lpszFileExtension As Long
  34. dwExemptDelta As Long
  35. End Type
  36. Private Declare Function FindFirstUrlCacheEntry Lib "wininet.dll" Alias "FindFirstUrlCacheEntryA" ( _
  37. ByVal lpszSearchPattern As String, _
  38. ByVal lpCacheInfo As Long, _
  39. lpdwFirstCacheEntryInfoBufferSize As Long) As Long
  40. Private Declare Function FindNextUrlCacheEntry Lib "wininet.dll" Alias "FindNextUrlCacheEntryA" ( _
  41. ByVal hEnumHandle As Long, _
  42. ByVal lpCacheInfo As Long, _
  43. lpdwNextCacheEntryInfoBufferSize As Long) As Long
  44. Private Declare Function FindCloseUrlCache Lib "wininet.dll" ( _
  45. ByVal hEnumHandle As Long) As Long
  46. Private Declare Function GetUrlCacheEntryInfo Lib "wininet.dll" Alias "GetUrlCacheEntryInfoA" ( _
  47. ByVal lpszUrlName As String, _
  48. ByVal lpCacheInfo As Long, _
  49. lpdwCacheEntryInfoBufferSize As Long) As Long
  50. Private Declare Function DeleteUrlCacheEntry Lib "wininet.dll" Alias "DeleteUrlCacheEntryA" ( _
  51. ByVal lpszUrlName As String) As Long
  52. Private Declare Function PtrToStr Lib "kernel32" Alias "lstrcpyA" (ByVal RetVal As String, ByVal Ptr As Long) As Long
  53. Private Declare Function FileTimeToSystemTime Lib "kernel32" (lpFileTime As FILETIME, lpSystemTime As SYSTEMTIME) As Long
  54. Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal dwLength As Long)
  55. Private Declare Function LocalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal uBytes As Long) As Long
  56. Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
  57. Private Declare Function lstrcpyA Lib "kernel32" (ByVal RetVal As String, ByVal Ptr As Long) As Long
  58. Private Declare Function lstrlenA Lib "kernel32" (ByVal Ptr As Any) As Long
  59. Private hEnumHandle As Long
  60. Private ci As INTERNET_CACHE_ENTRY_INFO
  61. Private lPtrCI As Long
  62. Public Property Get CachedEntryCacheType() As Long
  63. CachedEntryCacheType = ci.CacheEntryType
  64. End Property
  65. Public Property Get CachedEntryExpireTime() As Date
  66. On Local Error Resume Next
  67. Dim dExpire As Date
  68. Dim stSystemTime As SYSTEMTIME
  69. Dim lReturnValue As Long
  70. lReturnValue = FileTimeToSystemTime(ci.ExpireTime, stSystemTime)
  71. With stSystemTime
  72. dExpire = CDate(.wMonth & "/" & .wDay & "/" & .wYear & " " & .wHour & ":" & .wMinute & ":" & .wSecond)
  73. End With
  74. CachedEntryExpireTime = dExpire
  75. End Property
  76. Public Property Get CachedEntryFileExtension() As String
  77. Dim strData As String
  78. Dim lReturnValue As Long
  79. Dim iPosition As Long
  80. strData = Space(250)
  81. lReturnValue = PtrToStr(strData, ci.lpszFileExtension)
  82. If lReturnValue Then
  83. iPosition = InStr(strData, Chr(0))
  84. CachedEntryFileExtension = Left$(strData, iPosition - 1)
  85. End If
  86. End Property
  87. Public Property Get CachedEntryLastAccessTime() As Date
  88. Dim dExpire As Date
  89. Dim stSystemTime As SYSTEMTIME
  90. Dim lReturnValue As Long
  91. lReturnValue = FileTimeToSystemTime(ci.LastAccessTime, stSystemTime)
  92. With stSystemTime
  93. dExpire = CDate(.wMonth & "/" & .wDay & "/" & .wYear & " " & .wHour & ":" & .wMinute & ":" & .wSecond)
  94. End With
  95. CachedEntryLastAccessTime = dExpire
  96. End Property
  97. Public Property Get CachedEntryLastModifiedTime() As Date
  98. Dim dExpire As Date
  99. Dim stSystemTime As SYSTEMTIME
  100. Dim lReturnValue As Long
  101. lReturnValue = FileTimeToSystemTime(ci.LastModifiedTime, stSystemTime)
  102. With stSystemTime
  103. dExpire = CDate(.wMonth & "/" & .wDay & "/" & .wYear & " " & .wHour & ":" & .wMinute & ":" & .wSecond)
  104. End With
  105. CachedEntryLastModifiedTime = dExpire
  106. End Property
  107. Public Property Get CachedEntryLastSyncTime() As Date
  108. Dim dExpire As Date
  109. Dim stSystemTime As SYSTEMTIME
  110. Dim lReturnValue As Long
  111. lReturnValue = FileTimeToSystemTime(ci.LastSyncTime, stSystemTime)
  112. With stSystemTime
  113. dExpire = CDate(.wMonth & "/" & .wDay & "/" & .wYear & " " & .wHour & ":" & .wMinute & ":" & .wSecond)
  114. End With
  115. CachedEntryLastSyncTime = dExpire
  116. End Property
  117. Public Property Get CachedEntryFileName() As String
  118. Dim strData As String
  119. Dim lReturnValue As Long
  120. Dim iPosition As Long
  121. strData = String$(lstrlenA(ByVal ci.lpszLocalFileName), 0)
  122. lReturnValue = lstrcpyA(strData, ci.lpszLocalFileName)
  123. If lReturnValue Then CachedEntryFileName = strData
  124. End Property
  125. Public Property Get CachedEntrySourceURL() As String
  126. Dim strData As String
  127. Dim lReturnValue As Long
  128. Dim iPosition As Long
  129. strData = String$(lstrlenA(ci.lpszSourceUrlName), 0)
  130. lReturnValue = lstrcpyA(strData, ci.lpszSourceUrlName)
  131. If lReturnValue Then CachedEntrySourceURL = strData
  132. End Property
  133. Public Function DeleteCacheEntry(SourceUrl As String) As Boolean
  134. Dim lReturnValue As Long
  135. lReturnValue = DeleteUrlCacheEntry(SourceUrl)
  136. DeleteCacheEntry = CBool(lReturnValue)
  137. End Function
  138. Public Function FindEntryInCache(Url As String) As Boolean
  139. Dim lReturnValue As Long, lSizeOfStruct As Long
  140. lReturnValue = GetUrlCacheEntryInfo(Url, 0&, lSizeOfStruct)
  141. If lPtrCI Then LocalFree lPtrCI
  142. lPtrCI = LocalAlloc(LMEM_FIXED, lSizeOfStruct)
  143. If lPtrCI Then
  144. CopyMemory ByVal lPtrCI, lSizeOfStruct, 4
  145. lReturnValue = GetUrlCacheEntryInfo(Url, lPtrCI, lSizeOfStruct)
  146. CopyMemory ci, ByVal lPtrCI, Len(ci)
  147. LocalFree lPtrCI
  148. End If
  149. FindEntryInCache = CBool(lReturnValue)
  150. End Function
  151. Public Function FindFirstCacheEntry() As Boolean
  152. Dim lSizeOfStruct As Long
  153. If hEnumHandle <> 0 Then FindCloseUrlCache hEnumHandle
  154. hEnumHandle = FindFirstUrlCacheEntry(vbNullString, 0&, lSizeOfStruct)
  155. If lPtrCI Then LocalFree lPtrCI
  156. lPtrCI = LocalAlloc(LMEM_FIXED, lSizeOfStruct)
  157. If lPtrCI Then
  158. CopyMemory ByVal lPtrCI, lSizeOfStruct, 4
  159. hEnumHandle = FindFirstUrlCacheEntry(ByVal vbNullString, lPtrCI, lSizeOfStruct)
  160. CopyMemory ci, ByVal lPtrCI, Len(ci)
  161. End If
  162. FindFirstCacheEntry = CBool(hEnumHandle)
  163. End Function
  164. Public Function FindNextCacheEntry() As Boolean
  165. Dim lReturnValue As Long, lSizeOfStruct As Long
  166. If hEnumHandle <> 0 Then
  167. lReturnValue = FindNextUrlCacheEntry(hEnumHandle, 0&, lSizeOfStruct)
  168. If lPtrCI Then LocalFree lPtrCI
  169. lPtrCI = LocalAlloc(LMEM_FIXED, lSizeOfStruct)
  170. If lPtrCI Then
  171. CopyMemory ByVal lPtrCI, lSizeOfStruct, 4
  172. lReturnValue = FindNextUrlCacheEntry(hEnumHandle, lPtrCI, lSizeOfStruct)
  173. CopyMemory ci, ByVal lPtrCI, Len(ci)
  174. End If
  175. If lReturnValue <> 0 Then FindNextCacheEntry = CBool(lReturnValue)
  176. End If
  177. End Function
  178. Private Sub Class_Terminate()
  179. If hEnumHandle Then Call FindCloseUrlCache(hEnumHandle)
  180. End Sub
Еще нашел код, который копирует в буфер сам объект Image. Он у меня на веб-странице такой 1. Фильтром находится правильно. Имеет тип HTMLImg ("[Object HTMLImageElement]") Но при попытке добавления к ControlRange объекта HTMLImg получаю ошибку: "object does not support this property or method".
Листинг программы
  1. Sub Command1_Click()
  2. Dim sURL As String: sURL = "https://eu.battle.net/account/creation/tos.html?country=RUS"
  3. Dim appIE As Object 'SHDocVw.InternetExplorer
  4. Set appIE = CreateObject("InternetExplorer.Application")
  5. With appIE
  6. .Navigate sURL
  7. .Visible = True
  8. '.Silent = True
  9. '.FullScreen = True
  10. Do While (.Busy Or .readyState <> 4): DoEvents: Loop
  11. Dim D As Object 'MSHTML.HTMLDocument
  12. Set D = .Document
  13. End with
  14. 'Dim f As Object
  15. 'Set f = D.getElementById("sec-string") '// input captcha
  16. 'D.Forms("creation").All("captchaInput").Value = "captchaDecode"
  17. Dim x, ctrlRange
  18. For Each x In appIE.Document.All
  19. If UCase(x.tagName) = UCase("IMG") Then
  20. ' If InStr(1, UCase(x.src), UCase(imgurl), 1) > 0 Then
  21. Stop
  22. Set ctrlRange = appIE.Document.body.createControlRange()
  23. 'Debug.Print x.tagName, x.src
  24. ctrlRange.Add (x)
  25. Clipboard.Clear
  26. ctrlRange.execCommand ("Copy")
  27. SavePicture Clipboard.GetData, App.Path & "\1.bmp" ' is used to save the picture to your hard drive
  28. Picture1.Picture = Clipboard.GetData
  29. Stop
  30. 'Exit For
  31. ' End If
  32. End If
  33. Next
  34. end sub

Решение задачи: «Как загрузить изображение с WEB страницы, не используя его URL адрес»

textual
Листинг программы
  1. using System;
  2. using mshtml;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Runtime.InteropServices;
  10.  
  11. namespace Battle_net_Download_Captcha_cs
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         public Form1()
  16.         {
  17.             InitializeComponent();
  18.         }
  19.  
  20.         [ComImport, InterfaceType((short)1), Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
  21.         private interface IHTMLElementRenderFixed
  22.         {
  23.             void DrawToDC(IntPtr hdc);
  24.             void SetDocumentPrinter(string bstrPrinterName, IntPtr hdc);
  25.         }
  26.  
  27.  
  28.         void GetImage(string id)
  29.         {
  30.             HtmlDocument D = webBrowser1.Document;
  31.            
  32.             HtmlElement e = D.GetElementById(id);
  33.  
  34.             int i = 0;
  35.  
  36.             MessageBox.Show("Процедура");
  37.  
  38.             //foreach (mshtml.IHTMLImgElement img in webBrowser1.Document.Images)
  39.             //{
  40.             //    MessageBox.Show("Картинка");
  41.  
  42.             HtmlElementCollection collection = D.Images;
  43.             foreach (HtmlElement c in collection)
  44.             {
  45.                 MessageBox.Show(c.Id);
  46.  
  47.                 IHTMLImgElement img = (IHTMLImgElement)c.DomElement; // e.DomElement (for parsed element)
  48.                 IHTMLElementRenderFixed render = (IHTMLElementRenderFixed)img;
  49.  
  50.                 Bitmap bmp = new Bitmap(img.width, img.height);
  51.                 Graphics g = Graphics.FromImage(bmp);
  52.                 IntPtr hdc = g.GetHdc();
  53.                 render.DrawToDC(hdc);
  54.                 g.ReleaseHdc(hdc);
  55.  
  56.                 bmp.Save("C:\\temp\\captcha" + i + ".png");
  57.  
  58.                 MessageBox.Show("Готово");
  59.  
  60.                 i ++;
  61.             }
  62.             //return bmp;
  63.         }
  64.  
  65.  
  66.         private void button1_Click(object sender, EventArgs e)
  67.         {
  68.             webBrowser1.Navigate("https://eu.battle.net/account/creation/tos.html?country=RUS");
  69.         }
  70.  
  71.         private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
  72.         {
  73.             if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
  74.                 return;
  75.  
  76.             while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
  77.             {
  78.                 Application.DoEvents();
  79.                 //System.Threading.Thread.Sleep(100);
  80.             }
  81.  
  82.             //captchaInput
  83.             //Bitmap img = GetImage("sec-string");
  84.  
  85.             GetImage("sec-string");
  86.         }
  87.     }
  88. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 4.333 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы