使用 VBA 和 Selenium 在 Chrome 中获取当前网址

问题描述 投票:0回答:2

有没有办法在 Excel 中使用 VBA 来获取 Chrome 的最后一个活动实例/选项卡的 url?

vba selenium-chromedriver
2个回答
0
投票

所以我快速浏览了一下,如果您的脚本中有当前打开的浏览器的驱动程序对象,这似乎很容易。

在此示例中,我打开了 chrome 浏览器的一个新实例,因此我拥有驱动程序对象,并使用“driver.Url”命令获取当前活动选项卡 Url。

Dim driver As New WebDriver

Private Sub getUrl()
    driver.Start "Chrome"
    driver.Get "https://www.google.com/"
    MsgBox (driver.Url)
End Sub

0
投票

首先,转到

Tools->Reference-> Select UIAutomationClient
,然后调用函数
Chrome_GetCurrentURL()


Function GetChrome(ByRef uia As CUIAutomation) As IUIAutomationElement
    
    
    'Dim uia As New CUIAutomation
    Dim el_Desktop As IUIAutomationElement
    Set el_Desktop = uia.GetRootElement
    
    Dim el_ChromeWins As IUIAutomationElementArray
    Dim el_ChromeWin As IUIAutomationElement
    Dim cnd_ChromeWin As IUIAutomationCondition

    ' check the window with class name as "Chrome_WidgetWin_1"
    Set cnd_ChromeWin = uia.CreatePropertyCondition(UIA_ClassNamePropertyId, "Chrome_WidgetWin_1")
    Set el_ChromeWins = el_Desktop.FindAll(TreeScope_Children, cnd_ChromeWin)
    Set el_ChromeWin = Nothing
    
    
    If el_ChromeWins.Length = 0 Then
        Debug.Print """Chrome_WidgetWin_1"" not found"
        Exit Function
    End If
    
    Dim count_ChromeWins As Integer
    For count_ChromeWins = 0 To el_ChromeWins.Length - 1
        CurWinTitle = el_ChromeWins.GetElement(count_ChromeWins).CurrentName
        If (InStr(1, CurWinTitle, "Chrome")) Then
            Set el_ChromeWin = el_ChromeWins.GetElement(count_ChromeWins)
            Exit For
        End If

    Next
    If el_ChromeWin Is Nothing Then
        Debug.Print "No Chrome Window Found"
        Exit Function
    End If
    Set GetChrome = el_ChromeWin
End Function


Function Chrome_GetCurrentURL()

    Dim strURL As String
    Dim uia As New CUIAutomation
    Dim el_ChromeWin As IUIAutomationElement
    Set el_ChromeWin = GetChrome(uia)
    Debug.Print "1-" & el_ChromeWin.CurrentName
    
    If el_ChromeWin Is Nothing Then
        Debug.Print "Chrome doe NOT exist"
        Exit Sub
    End If
    
    
    Dim cnd As IUIAutomationCondition
    Set cnd = uia.CreatePropertyCondition(UIA_NamePropertyId, "地址和搜索栏")
    
    Dim AddressBar As IUIAutomationElement
    Set AddressBar = el_ChromeWin.FindFirst(TreeScope_Subtree, cnd)
    'Debug.Print AddressBar.CurrentName
    strURL = AddressBar.GetCurrentPropertyValue(UIA_ValueValuePropertyId)
    Chrome_GetCurrentURL=strURL
End Function
© www.soinside.com 2019 - 2024. All rights reserved.