【问题标题】:How to apply SendKeys Keys.Enter (or Keys.Return) using Selenium in Excel?如何在 Excel 中使用 Selenium 应用 SendKeys Keys.Enter(或 Keys.Return)?
【发布时间】:2020-10-12 23:55:06
【问题描述】:

我正在整理一个词汇表并整理一个宏以从词汇表.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

【问题讨论】:

  • 你在哪一行得到错误?此外,我看不出在您开始输入后手动按 Enter 对搜索结果有何影响。
  • 我在 Driver.FindElementById("search").SendKeys Range("A" & count) + Keys.Return 上得到它。它不喜欢 Keys.Return。这很重要,因为有时自动完成中弹出的第一个单词不是我正在寻找的单词。它可能是一个较长的词,与我正在搜索的词具有相同的词根。在这种情况下,除非您按 Enter,否则不会显示正确的页面,然后它会在搜索框中返回具有准确拼写的页面。
  • 我也在试图弄清楚如何让它点击自动完成列表中的正确单词。虽然不太确定该怎么做。就像从元素之类的东西中查找元素一样。
  • 我修复了我遇到的对象错误。我忘了创建 Keys 对象,但 Keys.Return 仍然不想工作。我尝试了其他键,例如 Keys.ArrowLeft,它们工作正常,只是不是 Enter 或 Return

标签: excel vba selenium web-scraping


【解决方案1】:

我无法使用 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

结束子

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2014-09-16
    • 2021-11-30
    • 1970-01-01
    • 2021-06-24
    • 2020-04-05
    • 2021-05-09
    • 2013-02-23
    相关资源
    最近更新 更多