Search code examples
excelvbaseleniumweb-scraping

How to apply SendKeys Keys.Enter (or Keys.Return) using Selenium in Excel?


I'm putting together a vocabulary list and put together a macro to pull info from vocabulary.com. The search doesn't have a button so I have to use the enter key, but Keys.Enter is not working.

The macro still works because you don't necessarily have to press the enter key for the site to show the definition page for the top most autocomplete result that pops up as you type in the search field.

The problem is that not in every case is the top most suggested result the word I am looking for. I need to get that Enter keystroke to work for this macro to be 100% useful.

Sub VocabularyWebScraper()
'Application.ScreenUpdating = False

Dim Driver As New Selenium.ChromeDriver
Dim Keys As Selenium.Keys
Dim count As Long

Sheets("Vocabulary.com Scraping").Activate

Set Driver = CreateObject("Selenium.ChromeDriver")
Set Keys = CreateObject("Selenium.Keys")
count = 1

While (Len(Range("A" & count)) > 0)
    
    Driver.Get "https://www.vocabulary.com/dictionary/"
    Driver.FindElementById("search").SendKeys Range("A" & count) + Keys.Enter
  
    Driver.Wait 1000
    
    On Error Resume Next
    Range("B" & count) = Driver.FindElementByClass("short").Text
    Range("C" & count) = Driver.FindElementByClass("long").Text
    
    count = count + 1

Wend

Driver.Quit

'Application.ScreenUpdating = True

End Sub

Solution

  • I wasn't able to get the enter key to work, but just in case anyone else wants to pull definitions from Vocabularly.com here is what worked. I ended up just clicking the button of the specific word I was looking for. Worked perfectly.

    Sub VocabularyWebScraper()
    
    Application.ScreenUpdating = False
    
    Dim Driver As New Selenium.ChromeDriver
    Dim count As Long
    Dim word As String
    
    Sheets("Vocab Web Scraping").Activate
    
    Set Driver = CreateObject("Selenium.ChromeDriver")
    count = 1
    
    While (Len(Range("A" & count)) > 0)
        
        word = Range("A" & count)
    
        Driver.Get "https://www.vocabulary.com/dictionary/"
        Driver.FindElementById("search").SendKeys word
        Driver.Wait 1000
        Driver.FindElementByCss("li[word='" + word + "']").Click
        Driver.Wait 2000
        
        On Error Resume Next
        Range("B" & count) = Driver.FindElementByClass("short").Text
        Range("C" & count) = Driver.FindElementByClass("long").Text
        
        count = count + 1
    
    Wend
    
    Driver.Quit
    
    Application.ScreenUpdating = True
    

    End Sub