单击已打开的浏览器窗口中的href链接

时间:2016-06-07 06:44:48

标签: html vbscript qtp browser-automation

在下面的代码中,我试图点击www.google.co.in网站上的“关于”链接(href)。这适用于IE11(Windows 10),但不适用于IE10(Windows 7)。这是否依赖于机器。如果不是什么是正确的代码?

请记住,我正在尝试点击已打开的浏览器窗口中的链接。

Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
    On Error Resume Next    ' sometimes more web pages are counted than are open
    my_url = objShell.Windows(x).Document.Location
    my_title = objShell.Windows(x).Document.Title

    'You can use my_title of my_url, whichever you want
    If my_title Like "Google" & "*" Then   'identify the existing web page
        Set ie = objShell.Windows(x)
        Exit For
    Else
    End If
Next

Dim LinkHref
Dim a

LinkHref = "//www.google.co.in/intl/en/about.html?fg=1"

For Each a In ie.Document.GetElementsByTagName("A")
  If LCase(a.GetAttribute("href")) = LCase(LinkHref) Then
    a.Click
    Exit For  ''# to stop after the first hit
  End If
Next

2 个答案:

答案 0 :(得分:2)

您可以在QTP中使用描述性编程来实现目标(如果您由于某种原因不想使用对象存储库)。此代码应该为您提供一个示例,说明您可以执行的操作:

Dim oDesc ' create a Description object for objects of class Link
Set oDesc = Description.Create
oDesc("micclass").value = "Link"

'Find all the Links in the browser using ChildObjects
Set obj = Browser("title=Google").Page("title=Google").ChildObjects(oDesc) 

Dim i
'obj.Count value has the number of links in the page
For i = 0 to obj.Count - 1   ' indexed from zero, so use 0 to Count -1
   'get the name of all the links in the page           
    If obj(i).GetROProperty("innerhtml")= LinkHref Then 
        obj(i).Click 'click the link if it matched the href you specfied
        Exit For ' no need to carry on the loop if we found the right link
    End If 
Next

如果你只需要使用vbscript,你可以这样做:

Dim oShell : Set oShell = CreateObject("Shell.Application")
Dim oWindow
For Each oWindow In oShell.Windows
    If InStr(oWindow.FullName, "iexplore") > 0 Then 
        If InStr(1, oWindow.Document.Title, "Google", vbTextCompare) > 0 Then
            Set ieApp = oWindow
            Exit For
        End If
    End If
Next

LinkHref = "//www.google.co.in/intl/en/about.html?fg=1"

For Each linky In ieApp.Document.GetElementsbyTagName("a")
    If LCase(linky.GetAttribute("href")) = LCase(LinkHref) Then
        linky.Click
        Exit For
    End If
Next

这几乎是Ansgar给出的答案,但是需要额外的一点来修复对象错误。只有一个浏览器窗口有Document.Title,并且循环正在处理每个打开的窗口,因此当循环尝试非IE窗口时会出现错误。此版本通过仅检查Document.Title来确定是否首先将窗口标识为IE实例。

答案 1 :(得分:1)

不了解QTP,但VBScript没有Like运算符。

这是在普通VBScript中附加到具有特定标题的IE窗口的常用方法:

Set app = CreateObject("Shell.Application")
For Each wnd In app.Windows
  If wnd.Name = "Internet Explorer" Then
    If InStr(1, wnd.Document.Title, "Google", vbTextCompare) > 0 Then
      Set ie = wnd
      Exit For
    End If
  End If
Next