我正在使用Excel VBA的Selenium Basic Wrapper,但是单击打开新选项卡的按钮后,我无法获取硒Web驱动程序将焦点切换到打开的新选项卡上,并转到请关闭原始选项卡。。相信使用Java Selenium应该可以实现,但是有什么方法可以通过excel VBA上的Selenium Basic包装器来实现?
尝试过使用bot.switchtopreviouswindow / nextwindow无效,Selenium甚至似乎都没有检测到作为现有窗口打开的新标签/窗口,还尝试过使用带有标题的switchwindow无效...
Private Sub CommandButton1_Click()
Dim bot As New ChromeDriver
Dim merchant As String
Dim promocode As Object
Dim number As Long
Dim test As Object
Dim testnumber As Integer
lastColumn = Sheets("Merchants").Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To lastColumn
bot.Get (Sheets("Merchants").Range("B" & i).Value)
merchant = Sheets("Merchants").Range("A" & i).Value
For Each promocode In bot.FindElementByClass("main_vouchers").FindElementsByClass("c")
number = Right(promocode.Attribute("id"), 6)
If IsEmpty(promocode) = True Then Exit For
promocode.FindElementByClass("go").Click
#This is the part I have problems with as after click, original page re-directs to another page, and new tab opens (which is the place I want focus on). Also, I need the original tab closed so that Chrome doesn't end up opening too many tabs due to the loop running. Appreciate the help!
Next promocode
Next i
End Sub
只需要Selenium将焦点切换到新打开的选项卡上,然后关闭旧/原始选项卡即可。
答案 0 :(得分:0)
以下对我有用的地方是您使用switchToNextWindow
,然后从当前窗口计数中减去1(您可能想先检查更多.windows.count> 1),然后在Windows集合中关闭该项目。
如果事先知道其中的一个,也可以使用.SwitchToWindowByName和.SwitchToWindowByTitle。可以从当前页面中提取出来。
'Ensure latest applicable driver e.g. ChromeDriver.exe in Selenium folder
'VBE > Tools > References > Add reference to selenium type library
Public Sub Example()
Dim d As WebDriver
Set d = New ChromeDriver
Const URL = "https://www.cuponation.com.sg/agoda-discount-code"
With d
.get URL
Debug.Print .Window.Title
.FindElementByCss(".go").Click
.SwitchToNextWindow
Debug.Print .URL '<= includes voucher code
'do something with new window
Debug.Print .Window.Title
.Windows.item(.Windows.Count - 1).Close 'close prior window
Debug.Print .Window.Title
Stop
.Quit
End With
End Sub