webbrowser 技巧2 (收藏)

    技术2022-05-11  125

    取得网页中特定的链接Private Sub Command1_Click()    WebBrowser1.Navigate "http://www.95557.com/svote.htm"End Sub

    Private Sub WebBrowser1_NavigateComplete2(ByVal pDisp As Object, URL As Variant)    Dim a        For Each a In WebBrowser1.Document.All        If a.tagname = "A" Then            If a.href = "http://tech.sina.com.cn/mobile/capture.shtml" Then                a.Click            End If        End If    NextEnd Sub

    Option ExplicitPrivate m_bDone As Boolean

    Private Sub Command1_Click()    If m_bDone Then        Dim doc As IHTMLDocument2        Set doc = WebBrowser1.Document        Dim aLink As HTMLLinkElement        Set aLink = doc.links(0)        aLink.Click    End IfEnd Sub

    Private Sub Form_Load()    WebBrowser1.Navigate "http://www.95557.com/svote.htm"End Sub

    Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)    m_bDone = TrueEnd Sub

    ==================================================

    The following code can be used to query and delete files in the internet cache (including cookies). A demonstration routine can be found at the bottom of this post. Note, the enumerated type eCacheType is not supported in Excel 97, but can be changed to a list of Public Constants eg. Public Const eNormal = &H1&.Option Explicit'--------------------------Types, consts and structuresPrivate Const ERROR_CACHE_FIND_FAIL As Long = 0Private Const ERROR_CACHE_FIND_SUCCESS As Long = 1Private Const ERROR_FILE_NOT_FOUND As Long = 2Private Const ERROR_ACCESS_DENIED As Long = 5Private Const ERROR_INSUFFICIENT_BUFFER As Long = 122Private Const MAX_CACHE_ENTRY_INFO_SIZE As Long = 4096Private Const LMEM_FIXED As Long = &H0Private Const LMEM_ZEROINIT As Long = &H40Public Enum eCacheTypeeNormal = &H1&eEdited = &H8&eTrackOffline = &H10&eTrackOnline = &H20&eSticky = &H40&eSparse = &H10000eCookie = &H100000eURLHistory = &H200000eURLFindDefaultFilter = 0&End EnumPrivate Type FILETIMEdwLowDateTime As LongdwHighDateTime As LongEnd TypePrivate Type INTERNET_CACHE_ENTRY_INFOdwStructSize As LonglpszSourceUrlName As LonglpszLocalFileName As LongCacheEntryType  As Long         'Type of entry returneddwUseCount As LongdwHitRate As LongdwSizeLow As LongdwSizeHigh As LongLastModifiedTime As FILETIMEExpireTime As FILETIMELastAccessTime As FILETIMELastSyncTime As FILETIMElpHeaderInfo As LongdwHeaderInfoSize As LonglpszFileExtension As LongdwExemptDelta  As LongEnd Type'--------------------------Internet Cache APIPrivate Declare Function FindFirstUrlCacheEntry Lib "Wininet.dll" Alias "FindFirstUrlCacheEntryA" (ByVal lpszUrlSearchPattern As String, lpFirstCacheEntryInfo As Any, lpdwFirstCacheEntryInfoBufferSize As Long) As LongPrivate Declare Function FindNextUrlCacheEntry Lib "Wininet.dll" Alias "FindNextUrlCacheEntryA" (ByVal hEnumHandle As Long, lpNextCacheEntryInfo As Any, lpdwNextCacheEntryInfoBufferSize As Long) As LongPrivate Declare Function FindCloseUrlCache Lib "Wininet.dll" (ByVal hEnumHandle As Long) As LongPrivate Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" Alias "DeleteUrlCacheEntryA" (ByVal lpszUrlName As String) As Long'--------------------------Memory APIPrivate Declare Function LocalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal uBytes As Long) As LongPrivate Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As LongPrivate Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal dwLength As Long)Private Declare Function lstrcpyA Lib "kernel32" (ByVal RetVal As String, ByVal Ptr As Long) As LongPrivate Declare Function lstrlenA Lib "kernel32" (ByVal Ptr As Any) As Long'Purpose     :  Deletes the specified internet cache file'Inputs      :  sCacheFile              The name of the cache file'Outputs     :  Returns True on success.'Author      :  Andrew Baker'Date        :  03/08/2000 19:14'Notes       :'Revisions   :Function InternetDeleteCache(sCacheFile As String) As BooleanInternetDeleteCache = CBool(DeleteUrlCacheEntry(sCacheFile))End Function'Purpose     :  Returns an array of files stored in the internet cache'Inputs      :  eFilterType             An enum which filters the files returned by their type'Outputs     :  A one dimensional, one based, string array containing the names of the files'Author      :  Andrew Baker'Date        :  03/08/2000 19:14'Notes       :'Revisions   :Function InternetCacheList(Optional eFilterType As eCacheType = eNormal) As VariantDim ICEI As INTERNET_CACHE_ENTRY_INFODim lhFile As Long, lBufferSize As Long, lptrBuffer As LongDim sCacheFile As StringDim asURLs() As String, lNumEntries As Long'Determine required buffer sizelBufferSize = 0lhFile = FindFirstUrlCacheEntry(0&, ByVal 0&, lBufferSize)If (lhFile = ERROR_CACHE_FIND_FAIL) And (Err.LastDllError = ERROR_INSUFFICIENT_BUFFER) Then'Allocate memory for ICEI structurelptrBuffer = LocalAlloc(LMEM_FIXED, lBufferSize)If lptrBuffer Then'Set a Long pointer to the memory locationCopyMemory ByVal lptrBuffer, lBufferSize, 4'Call first find API passing it the pointer to the allocated memorylhFile = FindFirstUrlCacheEntry(vbNullString, ByVal lptrBuffer, lBufferSize)        '1 = successIf lhFile <> ERROR_CACHE_FIND_FAIL Then'Loop through the cacheDo'Copy data back to structureCopyMemory ICEI, ByVal lptrBuffer, Len(ICEI)If ICEI.CacheEntryType And eFilterType ThensCacheFile = StrFromPtrA(ICEI.lpszSourceUrlName)lNumEntries = lNumEntries + 1If lNumEntries = 1 ThenReDim asURLs(1 To 1)ElseReDim Preserve asURLs(1 To lNumEntries)End IfasURLs(lNumEntries) = sCacheFileEnd If'Free memory associated with the last-retrieved fileCall LocalFree(lptrBuffer)'Call FindNextUrlCacheEntry with buffer size set to 0.'Call will fail and return required buffer size.lBufferSize = 0Call FindNextUrlCacheEntry(lhFile, ByVal 0&, lBufferSize)'Allocate and assign the memory to the pointerlptrBuffer = LocalAlloc(LMEM_FIXED, lBufferSize)CopyMemory ByVal lptrBuffer, lBufferSize, 4&Loop While FindNextUrlCacheEntry(lhFile, ByVal lptrBuffer, lBufferSize)End IfEnd IfEnd If'Free memoryCall LocalFree(lptrBuffer)Call FindCloseUrlCache(lhFile)InternetCacheList = asURLsEnd Function'Purpose     :  Converts a pointer an ansi string into a string.'Inputs      :  lptrString                  A long pointer to a string held in memory'Outputs     :  The string held at the specified memory address'Author      :  Andrew Baker'Date        :  03/08/2000 19:14'Notes       :'Revisions   :Function StrFromPtrA(ByVal lptrString As Long) As String'Create bufferStrFromPtrA = String$(lstrlenA(ByVal lptrString), 0)'Copy memoryCall lstrcpyA(ByVal StrFromPtrA, ByVal lptrString)End Function'Demonstration routineSub Test()Dim avURLs As Variant, vThisValue As VariantOn Error Resume Next'Return an array of all internet cache filesavURLs = InternetCacheListFor Each vThisValue In avURLs'Print filesDebug.Print CStr(vThisValue)Next'Return the an array of all cookiesavURLs = InternetCacheList(eCookie)If MsgBox("Delete cookies?", vbQuestion + vbYesNo) = vbYes ThenFor Each vThisValue In avURLs'Delete cookiesInternetDeleteCache CStr(vThisValue)Debug.Print "Deleted " & vThisValueNextElseFor Each vThisValue In avURLs'Print cookie filesDebug.Print vThisValueNextEnd IfEnd Sub

    =======================================================分析网页内容,取得<SCRIPT>Option Explicit

    Private Sub Form_Load()    WebBrowser1.Navigate "http://test/index.html"End Sub

    Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)    Dim sTemp As String    Dim outStr As String    Dim i As Integer    Dim beginPos As Long    Dim endPos As Long        sTemp = WebBrowser1.Document.documentelement.InnerHTML    'Text1.Text = sTemp    i = 1    Do While i <> 0        i = InStr(1, sTemp, "<SCRIPT")        If i <> 0 Then            outStr = Left(sTemp, i - 1)            sTemp = Right(sTemp, Len(sTemp) - i - 6)            i = InStr(1, sTemp, "</SCRIPT>")            If i <> 0 Then                sTemp = Right(sTemp, Len(sTemp) - i - 8)            End If            sTemp = outStr & sTemp        End If    Loop    WebBrowser1.Document.write sTemp    'Text2.Text = sTempEnd Sub

     

    =======================================================================

     

    在"通用"里定义dim myhWnd() as long,dim i as integer然后dim newWin as form2set newWin = new form2newWin.ShowSet ppDisp = newWin.form2.object

    redim myhWnd(i) as longmyhwnd(i)=newWin.hwndi=i+1

     

    ----------------------------------------------------------------

     

    -----------------------------------------------------------------------------------------

     

    ===================================================================================控制字体大小

    webbrowser1 ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(4 - Index)

    index=0-4表示从最大到最小~~

    最小的话,index=4,呵呵

    webbrowser1 ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER,0可以遍历页面,也可以~~

    如果你只是想得到网页中的所有连接,这样就OK了~~

    Option Explicit

    Private Sub Command1_Click()Command1.Enabled = FalseWebBrowser1.Navigate2 Text1.TextEnd Sub

    Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)

    Dim x As LongList1.Clear

    For x = 0 To WebBrowser1.Document.Links.length - 1    List1.AddItem WebBrowser1.Document.Links.Item(x)Next xCommand1.Enabled = TrueEnd Sub

    Private Sub WebBrowser1_StatusTextChange(ByVal Text As String)Label3 = TextEnd Sub

     

    ==================================================================================================Public Class Form1    Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "    'Omitted#End Region

        Private Sub Button1_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles Button1.Click            AxWebBrowser1.Navigate(TextBox1.Text)    End Sub

        Private Sub AxWebBrowser1_NewWindow2(ByVal sender As Object, _        ByVal e As AxSHDocVw.DWebBrowserEvents2_NewWindow2Event) _        Handles AxWebBrowser1.NewWindow2            'MessageBox.Show(AxWebBrowser1.Height & ":" & AxWebBrowser1.Width)

                'MessageBox.Show(doc.body.innerHTML)            Dim frmWB As Form1            frmWB = New Form1()

                frmWB.AxWebBrowser1.RegisterAsBrowser = True            'frmWB.AxWebBrowser1.Navigate2("about:blank")            e.ppDisp = frmWB.AxWebBrowser1.Application            frmWB.Visible = True            'MessageBox.Show(frmWB.AxWebBrowser1.Height & ":" & frmWB.AxWebBrowser1.Width)    End Sub

        Private Sub AxWebBrowser1_WindowSetHeight(ByVal sender As Object, _        ByVal e As AxSHDocVw.DWebBrowserEvents2_WindowSetHeightEvent) _        Handles AxWebBrowser1.WindowSetHeight            'MessageBox.Show("In SetHeight" & Me.Height & ":" & e.height)            Dim heightDiff As Integer            heightDiff = Me.Height - Me.AxWebBrowser1.Height            Me.Height = heightDiff + e.height    End Sub

        Private Sub AxWebBrowser1_WindowSetWidth(ByVal sender As Object, _        ByVal e As AxSHDocVw.DWebBrowserEvents2_WindowSetWidthEvent) _        Handles AxWebBrowser1.WindowSetWidth            'MessageBox.Show("In SetWidth" & Me.Width & ":" & e.width)            Dim widthDiff As Integer            widthDiff = Me.Width - Me.AxWebBrowser1.Width            Me.Width = widthDiff + e.width    End Sub

    End Class

     

     

    ===================================================================================================替换TEXTBOX的菜单。Public Declare Function GetWindowLong Lib "user32" Alias _                      "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As                   Long) _                      As Long                  Public Declare Function SetWindowLong Lib "user32" Alias _                      "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As                   Long, _                      ByVal dwNewLong As Long) As Long                  Private Declare Function CallWindowProc Lib "user32" Alias _                      "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd                   _                      As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal _                      lParam As Long) As Long                  Public Function SubClass_WndMessage(ByVal hWnd As _                      OLE_HANDLE,ByVal Msg As OLE_HANDLE, ByVal wParam As                   OLE_HANDLE, _                      ByVal lParam As Long) As Long                      If Msg <> WM_CONTEXTMENU Then                          SubClass_WndMessage = CallWindowProc(OldWinProc, _                              hWnd, Msg,wParam, lParam)                              ' 如果消息不是WM_CONTEXTMENU,就调用系统的窗口处理函数                          Exit Function                      End If                      SubClass_WndMessage = True                  End Function

                      >>步骤4----在窗体中加入如下代码:                  Private Const GWL_WNDPROC = (-4)

                      Private Sub Text1_MouseDown(Button As Integer, Shift As _                      Integer, X As Single, Y As Single)

                          If Button = 1 Then Exit Sub                      OldWinProc = GetWindowLong(Text1.hWnd, GWL_WNDPROC)                      ' 取得窗口函数的地址                      Call SetWindowLong(Text1.hWnd, GWL_WNDPROC, AddressOf _                          SubClass_WndMessage)                          ' 用SubClass_WndMessage代替窗口函数处理消息                  End Sub

                      Private Sub Text1_MouseUp(Button As Integer, Shift _                      As Integer, X As Single, Y As Single)                      If Button = 1 Then Exit Sub                      Call SetWindowLong(Text1.hWnd, GWL_WNDPROC, OldWinProc)                      ' 恢复窗口的默认函数                      PopupMenu a                      ' 弹出自定义菜单                  End Sub

    ================================================================================================选择网页上的内容。

    '引用 Microsoft HTML Object Library

        Dim oDoc As HTMLDocument    Dim oElement As Object    Dim oTxtRgn As Object    Dim sSelectedText As String        Set oDoc = WebBrowser1.Document'获得文档对象    Set oElement = oDoc.getElementById("T1")'获得ID="T1"的对象    Set oTxtRgn = oDoc.selection.createRange'获得文档当前正选择的区域对象       sSelectedText = oTxtRgn.Text'选择区域文本赋值

        oElement.Focus'"T1"对象获得焦点

        oElement.Select'全选对象"T1"

        Debug.Print "你选择了文本:" & sSelectedText

    上面这段儿还附送了其他功能,呵呵。精简一下是这样:    Dim oDoc As Object    Dim oTxtRgn As Object    Dim sSelectedHTML As String        Set oDoc = WebBrowser1.Document '获得文档对象    Set oTxtRgn = oDoc.selection.createRange '获得文档当前正选择的区域对象       sSelectedHTML = oTxtRgn.htmlText '选择区域文本赋值

        Text1.Text=sSelectedHTML '文本框显示抓取得HTML源码    ......'或者继续分析源码

    ==================================================================================Private Declare Function URLDownloadToFile Lib "urlmon" _   Alias "URLDownloadToFileA" _  (ByVal pCaller As Long, _   ByVal szURL As String, _   ByVal szFileName As String, _   ByVal dwReserved As Long, _   ByVal lpfnCB As Long) As Long Private Sub Command1_Click()

       Dim sourceUrl As String   Dim targetFile As String   Dim hfile As Long      sourceUrl = "http://123.com/123.asp?姓名=张&性别=女"   targetFile = "c:/temp/xxx.html"   hfile = URLDownloadToFile(0&, sourceUrl, targetFile, 0&, 0&)   End Sub

    URLDownloadToFile:说明:Downloads bits from the Internet and saves them to a file.

    适用于:VB4-32,5,6声明:Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

    操作系统支持:Requires Windows NT 4.0 or later; Requires Windows 95 or later

    库文件Urlmon 参数:

    pCaller:Address of the controlling IUnknown interface of the calling Microsoft?ActiveX?component (if the caller is an ActiveX component). If the calling application is not an ActiveX component, this value can be set to NULL. Otherwise, the caller is a Component Object Model (COM) object that is contained in another component (such as an ActiveX control within the context of an HTML page). This parameter represents the outermost IUnknown of the calling component. The function attempts the download within the context of the ActiveX client framework and allows the caller's container to receive callbacks on the progress of the download.

    szURL:Address of a string value containing the URL to be downloaded. Cannot be set to NULL.

    szFileName:Address of a string value containing the name of the file to create for bits that come from the download.

    dwReserved:Reserved. Must be zero.

    lpfnCB:Address of the caller's IBindStatusCallback interface. URLDownloadToFile calls this interface's IBindStatusCallback::OnProgress method on a connection activity, including the arrival of data. IBindStatusCallback::OnDataAvailable is never called. Implementing IBindStatusCallback::OnProgress allows a caller to implement a user interface or other progress monitoring functionality. It also allows the download operation to be canceled by returning E_ABORT from the IBindStatusCallback::OnProgress call. This can be set to NULL. 

    返回值:Returns one of the following values:E_OUTOFMEMORYThe buffer length is invalid or there was insufficient memory to complete the operation. S_OKThe operation succeeded. 

    具体的解释我就不翻译了================================================================================================

     

    Option ExplicitEnum OLECMDID     OLECMDID_OPEN = 1     OLECMDID_NEW = 2     OLECMDID_SAVE = 3     OLECMDID_SAVEAS = 4     OLECMDID_SAVECOPYAS = 5     OLECMDID_PRINT = 6     OLECMDID_PRINTPREVIEW = 7     OLECMDID_PAGESETUP = 8     OLECMDID_SPELL = 9     OLECMDID_PROPERTIES = 10     OLECMDID_CUT = 11     OLECMDID_COPY = 12     OLECMDID_PASTE = 13     OLECMDID_PASTESPECIAL = 14     OLECMDID_UNDO = 15     OLECMDID_REDO = 16     OLECMDID_SELECTALL = 17     OLECMDID_CLEARSELECTION = 18     OLECMDID_ZOOM = 19     OLECMDID_GETZOOMRANGE = 20     OLECMDID_UPDATECOMMANDS = 21     OLECMDID_REFRESH = 22     OLECMDID_STOP = 23     OLECMDID_HIDETOOLBARS = 24     OLECMDID_SETPROGRESSMAX = 25     OLECMDID_SETPROGRESSPOS = 26     OLECMDID_SETPROGRESSTEXT = 27     OLECMDID_SETTITLE = 28     OLECMDID_SETDOWNLOADSTATE = 29     OLECMDID_STOPDOWNLOAD = 30     OLECMDID_ONTOOLBARACTIVATED = 31     OLECMDID_FIND = 32     OLECMDID_DELETE = 33     OLECMDID_HTTPEQUIV = 34     OLECMDID_HTTPEQUIV_DONE = 35     OLECMDID_ENABLE_INTERACTION = 36     OLECMDID_ONUNLOAD = 37End Enum

    Enum OLECMDF    OLECMDF_SUPPORTED = 1    OLECMDF_ENABLED = 2    OLECMDF_LATCHED = 4    OLECMDF_NINCHED = 8End Enum

    Enum OLECMDEXECOPT    OLECMDEXECOPT_DODEFAULT = 0    OLECMDEXECOPT_PROMPTUSER = 1    OLECMDEXECOPT_DONTPROMPTUSER = 2    OLECMDEXECOPT_SHOWHELP = 3End Enum

    Private Sub brwSaveAs_Click()    On Error Resume Next

        Screen.MousePointer = vbHourglass    DoEvents    Web1(SSTab1.Tab).ExecWB OLECMDID_SAVEAS, OLECMDEXECOPT_DONTPROMPTUSER, "aa", "(*.txt)"    If Err.Number <> 0 Then        MsgBox "无法另存新文件!"    End If    Screen.MousePointer = vbDefaultEnd Sub

    帮不了你了,这是webbrowser相关的一些资料,希望对你有用=========================================================================================================把WEBBROWSER1装到PICTURE里面

    Set Me.WebBrowser1.Container = Me.Picture1

     


    最新回复(0)