мой код открывает 2 дочерних окна. После выполнения операций с каждым из них мне нужно закрыть окна и вернуться к родительскому окну.
Варианта в виде driver.switchToParentWindow нет. Есть только driver.switchToPreviousWindow.
Например: я закрываю 2-е дочернее окно → затем driver.switchToPreviousWindow переключает управление обратно на 1-е дочернее окно, но когда я закрываю это окно и делаю driver.SwitchToPreviousWindow, он ищет недавно закрытое 2-е дочернее окно, тогда как я хочу, чтобы он переключил управление к родительскому окну.
Я пробовал везде искать решение, но, похоже, не могу найти его, использующего Selenium VBA, чтобы вернуться к родительскому окну.
Вот мой код:
For a = 9 To LastRow
If Wb.Sheets(DestName).Cells(a, 3).Text = "Report Name" Then
'Checking if cell has 'Report Name'
StoreFile = Wb.Sheets(DestName).Cells(a, 4).Text
Debug.Print StoreFile
'Click on Report
Set myelement = driver.FindElementByLinkText(StoreFile) 'Click on report by name
Debug.Print myelement.Text
If myelement Is Nothing Then
GoTo endTry
ElseIf StoreFile = "CBD_Yoplait" Then
StoreFile = "CBD_Yoplait" & ".Category Buyer Dynamic"
Debug.Print StoreFile
Set myelement = driver.FindElementByLinkText(StoreFile)
myelement.Click
Else
myelement.Click
End If
'1st child window opens
driver.SwitchToNextWindow
Application.Wait (Now + TimeValue("0:0:07"))
'Click on 'Report Home'
Set myelement = driver.FindElementByXPath("//*
[@id = ""ribbonToolbarTabsListContainer""]/div[1]/table/tbody/tr/td[3]")
If myelement Is Nothing Then
MsgBox ("no element found")
Else
myelement.Click
End If
'Click on 'Export'
Set myelement = driver.FindElementByXPath("//*
[@id = ""RptHomeMenu_""]/tbody/tr/td/div/div[16]/a/div[2]")
If myelement Is Nothing Then
MsgBox ("no element found")
Else
myelement.Click
End If
'Click on 'Excel with Formatting'
Set myelement = driver.FindElementByXPath("//*
[@id = ""RptHomeExportMenu_WEB-
INFxmllayoutsblocksHomeExportMenuLayoutxml""]
/tbody/tr/td/div/div[8]/a/div[2]")
If myelement Is Nothing Then
MsgBox ("no element found")
Else
myelement.Click
End If
'Opend 2nd child window
driver.SwitchToNextWindow
Application.Wait (Now + TimeValue("0:0:05"))
'Click on 'Export filter details'
Set myelement = driver.FindElementById("exportFilterDetails")
If myelement Is Nothing Then
MsgBox ("no element found")
Else
myelement.Click
End If
'Click on Export button
Set myelement = driver.FindElementById("3131")
If myelement Is Nothing Then
MsgBox ("no element found")
Else
myelement.Click
End If
Application.Wait (Now + TimeValue("0:0:08"))
FileSpec = StoreFile & ".xls*"
Debug.Print FileSpec
FileName = Dir(MyDir & FileSpec)
Debug.Print FileName
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(MyDir & FileName)
Do While FileName <> ""
If FileDateTime(MyDir & FileName) > MostRecentDate Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(MyDir & FileName)
End If
FileName = Dir
Loop
End If
MyFile = MostRecentFile
Debug.Print MyFile
ChDir MyDir
Set SrcWb = Workbooks.Open(MyDir + MyFile, UpdateLinks:=0)
'Saving as xls workbook
SrcWb.SaveAs DestFolder & MyFile, XlFileFormat.xlExcel8
Application.Wait (Now + TimeValue("0:0:04"))
Application.DisplayAlerts = True
SrcWb.Close
driver.Close
driver.SwitchToPreviousWindow
driver.Close
driver.SwitchToPreviousWindow ( Want to switch back to parent window)
Application.Wait (Now + TimeValue("0:0:08"))
endTry:
End If
Next a
Я использую Google Chrome, последняя версия Version -> 65.0.3325.162





После закрытия 1-е дочернее окно для переключения управления на родительское окно вместо driver.SwitchToPreviousWindow лучшим решением было бы использовать любой из методов:
SwitchToWindowByName ():
/// <summary>
/// Switch focus to the specified window by name.
/// </summary>
/// <param name = "name">The name of the window to activate</param>
/// <param name = "timeout">Optional timeout in milliseconds</param>
/// <param name = "raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Current web driver</returns>
public Window SwitchToWindowByName(string name, int timeout = -1, bool raise = true) {
try {
return session.windows.SwitchToWindowByName(name, timeout);
} catch (Errors.NoSuchWindowError) {
if (raise)
throw new Errors.NoSuchWindowError(name);
return null;
}
}
SwitchToWindowByTitle ():
/// <summary>
/// Switch focus to the specified window by title.
/// </summary>
/// <param name = "title">The title of the window to activate</param>
/// <param name = "timeout">Optional timeout in milliseconds</param>
/// <param name = "raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Current web driver</returns>
public Window SwitchToWindowByTitle(string title, int timeout = -1, bool raise = true) {
try {
return session.windows.SwitchToWindowByTitle(title, timeout);
} catch (Errors.NoSuchWindowError) {
if (raise)
throw new Errors.NoSuchWindowError(title);
return null;
}
}
Спасибо @DebanjanB, я взял идею из вашего решения, это было просто изменение одной строки 'driver.SwitchToWindowByTitle ("WindowTitle")', и это сработало.
Я взял идею из решения @ DebanjanB, это было просто однострочное изменение драйвера.SwitchToWindowByTitle ("WindowTitle") ', и оно сработало.
Поскольку его ответ привел к решению вашей проблемы, было бы кошерно проголосовать за и / или отметить его ответ как ответ на ваш вопрос.
Какой браузер вы используете? Можете ли вы воспроизвести в другом браузере? Я знаю, что это (была?) Известная проблема, по крайней мере, для Firefox.