如何在Excel中使用Selenium应用SendKeys Keys.Enter(或Keys.Return)?

问题描述 投票:0回答:2

我正在整理一个词汇列表并整理一个宏以从vocabulary.com 中提取信息。搜索没有按钮,所以我必须使用回车键,但是

Keys.Enter
不起作用。

该宏仍然有效,因为您不必按网站的 Enter 键即可显示当您在搜索字段中键入时弹出的最顶部自动完成结果的定义页面。

问题是,并非在所有情况下,最热门的建议结果都是我正在寻找的单词。我需要让 Enter 按键才能使这个宏 100% 有用。

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
excel vba selenium web-scraping
2个回答
0
投票

我无法让回车键起作用,但以防万一其他人想从 Vocabularly.com 中提取定义,这就是有效的方法。我最终只是单击了我要查找的特定单词的按钮。效果很好。

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

结束子


0
投票

您必须编写“Driver.SendKeys Driver.Keys.Enter”来模拟“Enter”。

© www.soinside.com 2019 - 2024. All rights reserved.