问题
I am trying to do google search based on some data in column A in Sheet1 .. and I need each cell content to be opened in new tab and do the search for that cell example: A1 has the word 'flower' so I expect to create a tab and navigate to google the do a search for that 'flower' then the next cell and so on and each search to be in a new tab Here's my try
Sub Test()
Dim bot As New ChromeDriver
Dim Keys As New Keys
bot.Get "https://www.google.com"
'search for items in column A
bot.ExecuteScript "window.open(arguments[0])", "https://www.google.com"
bot.SwitchToNextWindow
End Sub
I also tried that part
bot.FindElementById("gsr").SendKeys Range("A1").Value
bot.SendKeys bot.Keys.Enter
bot.SwitchToNextWindow
But I couldn't create a new tab
回答1:
Try the following. You need to target the search box for text input.
Option Explicit
Public Sub Test()
Dim bot As ChromeDriver, keys As New keys, arr(), ws As Worksheet, i As Long
Set bot = New ChromeDriver
Set ws = ThisWorkbook.Worksheets("Sheet1") '<==Adjust to your sheet
arr = Application.Transpose(ws.Range("A1:A3")) '<== Adjust to your range
With bot
.Start "Chrome"
.get "https://google.com/"
For i = LBound(arr) To UBound(arr)
If Not IsEmpty(arr(i)) Then
If i > 1 Then
.ExecuteScript "window.open(arguments[0])", "https://google.com/"
.SwitchToNextWindow
End If
.FindElementByCss("[title=Search]").SendKeys arr(i)
End If
Next
End With
Stop '<==Delete me later
End Sub
Using a timed loop to find the element:
Option Explicit
Public Sub Test()
Dim bot As ChromeDriver, keys As New keys, arr(), ws As Worksheet, i As Long
Const MAX_WAIT_SEC As Long = 5
Dim ele As Object, t As Date
Set bot = New ChromeDriver
Set ws = ThisWorkbook.Worksheets("Sheet1") '<==Adjust to your sheet
arr = Application.Transpose(ws.Range("A1:A3")) '<== Adjust to your range
With bot
.Start "Chrome"
.get "https://google.com/"
For i = LBound(arr) To UBound(arr)
If Not IsEmpty(arr(i)) Then
If i > 1 Then
.ExecuteScript "window.open(arguments[0])", "https://google.com/"
.SwitchToNextWindow
End If
t = Timer
Do
DoEvents
On Error Resume Next
Set ele = .FindElementByCss("[title=Search]")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing
If Not ele Is Nothing Then
ele.SendKeys arr(i)
Else
Exit Sub
End If
End If
Next
End With
Stop '<==Delete me later
End Sub
来源:https://stackoverflow.com/questions/53381891/create-new-tab-for-each-google-search-by-selenium-in-excel-vba