无法使用 Selenium 和 C# 在 Google 主页上找到搜索框元素

Unable to locate the Search Box element on Google Home Page using Selenium and C#

为什么我会收到这个错误?:

OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"css selector","selector":"#gbqfq"}

这是我用来打开浏览器并在 google 搜索中搜索给定单词的代码:

 IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://google.com");

IWebElement element = driver.FindElement(By.Id("gbqfq"));
element.SendKeys("APPLES");

// Get the search results panel that contains the link for each result.
IWebElement resultsPanel = driver.FindElement(By.Id("search"));

// Get all the links only contained within the search result panel.
ReadOnlyCollection<IWebElement> searchResults = resultsPanel.FindElements(By.XPath(".//a"));

// Print the text for every link in the search results.
int resultCNT = 1;
foreach (IWebElement result in searchResults)
{
    if (resultCNT <= 5)
    {
        Console.WriteLine(result.Text);
    }
    else
    {
        break;
    }
    resultCNT ++;
}

有人知道可能是什么问题吗?谢谢

完整日志:

OpenQA.Selenium.NoSuchElementException
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"#gbqfq"}
  (Session info: chrome=84.0.4147.125)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementById(String id)
   at OpenQA.Selenium.By.<>c__DisplayClass16_0.<Id>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
   at $Program.$Main(String[] args) in C:\Users\gabri\source\repos\Example\Example\Program.cs:line 10

由于您的用例是打开浏览器并在 Google Home Page 中搜索给定的词,搜索框 HTML 如下:

<input class="gLFyf gsfi" maxlength="2048" name="q" type="text" jsaction="paste:puy29d" aria-autocomplete="both" aria-haspopup="false" autocapitalize="off" autocomplete="off" autocorrect="off" autofocus="" role="combobox" spellcheck="false" title="Search" value="" aria-label="Search" data-ved="0ahUKEwiq_ZvUyJvrAhXhzjgGHXBjBx4Q39UDCAQ">

因此,要识别 <input> 框,您可以使用以下任一方法 :

  • 姓名:

    driver.FindElement(By.Name("q")).SendKeys("gbqfq");
    
  • CssSelector:

    driver.FindElement(By.CssSelector("[name='q']")).SendKeys("APPLES");
    
  • XPath:

    driver.FindElement(By.XPath("//*[@name='q']")).SendKeys("APPLES");
    

此外,所需的元素是 JavaScript 启用的元素,因此要在元素中发送 字符序列 ,您必须引入 WebDriverWait 用于 ElementToBeClickable(),您可以使用以下任一 ocator 策略

  • 姓名:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.Name("q"))).SendKeys("APPLES");
    
  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("[name='q']"))).SendKeys("APPLES");
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*[@name='q']"))).SendKeys("APPLES");