在Excel VBA中按硒为每个Google搜索创建新标签

时间:2018-11-19 20:07:08

标签: excel vba excel-vba selenium web-scraping

我正在尝试基于Sheet1中A列中的某些数据进行google搜索..我需要在新选项卡中打开每个单元格内容并搜索该单元格 示例:A1的单词为“ flower”,因此我希望创建一个标签并导航到google,然后搜索该“ flower”,然后搜索下一个单元格,依此类推 并且每个搜索都在一个新标签中 这是我的尝试

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

我也尝试过那部分

bot.FindElementById("gsr").SendKeys Range("A1").Value
bot.SendKeys bot.Keys.Enter
bot.SwitchToNextWindow

但是我无法创建新标签页

1 个答案:

答案 0 :(得分:1)

尝试以下方法。您需要将搜索框定位为文本输入。

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

使用定时循环查找元素:

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