首页 > 解决方案 > 如何在 Excel 中使用 Selenium 应用 SendKeys Keys.Enter(或 Keys.Return)?

问题描述

我正在整理一个词汇表并整理一个宏来从词汇表中提取信息。搜索没有按钮,所以我必须使用回车键,但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

标签: excelvbaseleniumweb-scraping

解决方案


我无法使用 enter 键,但以防万一其他人想从 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

结束子


推荐阅读