Control new Google Chrome tab with Selenium VBA

Asked

Viewed 2,820 times

-2

I’m writing a code to liquidate some operations on a website. Directly from excel, through VBA, using the SELENIUM library, I wrote a code to log in and fill in fields with information directly from the spreadsheet. The code goes well until the moment it clicks on a field and opens a new tab (the tab would open the same way if it were manual). The problem is that when this new tab opens, it doesn’t respond to code commands, which keep sending commands to the initial tab where the code starts. My code is like this:

Sub Test()
Dim bot  As New WebDriver
Dim login As String, cpf As String, senha As String, comando As String
cpf = ThisWorkbook.Sheets(1).Cells(2, 7)
login = ThisWorkbook.Sheets(1).Cells(3, 7)
senha = ThisWorkbook.Sheets(1).Cells(4, 7)
comando = ThisWorkbook.Sheets(1).Cells(5, 7)
bot.Start "chrome", "www.site.com.br"
bot.Get "/"
bot.Wait 1000
bot.FindElementById("abrirModalLogin").Click
bot.Wait 500
bot.FindElementById("cpf").SendKeys cpf
bot.FindElementById("username").SendKeys login
bot.FindElementById("password").SendKeys senha
bot.Wait 500
bot.FindElementById("submit").Click
bot.Wait 500
bot.FindElementByXPath("//*[@id='menuPrincipal']/ul/li[4]/a").Click
bot.Wait 400 bot.FindElementByXPath("/html/body/header/div[1]/div[3]/nav/ul/li[4]/div/div[1]/ul[1]/li[1]/a").Click
bot.Wait 1000

I wonder if anyone has been through this and could tell me how to continue sending commands to the new tab open.

Thank you very much.

1 answer

0


You can do that with

bot.SwitchToWindowByTitle "Title"  'Substitui pelo título exato da nova janela

Or if you’ve only opened this new window

bot.SwitchToNextWindow

EDIT:

Here is a simple test to prove that the command SwitchToNextWindow toggle to the new tab:

Sub Test()

    Dim bot  As New WebDriver

    bot.Start "Chrome"
    bot.Get "https://www.google.com"
    bot.ExecuteScript ("window.open('http://www.facebook.com/')")
    bot.SwitchToNextWindow
    Debug.Print bot.Window.Title

End Sub

Returns :

Facebook - Log In or Sign Up
  • Thanks for the answer. But this command switches between windows and not between tabs. .

  • Switch yes between tabs.

  • Thank you so much! It worked!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.