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

问题描述

为什么我会收到此错误?:

conda env

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

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

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

完整日志:

 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 ++;
}

解决方法

由于您的用例是打开浏览器并在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>框,可以使用以下Locator Strategies之一:

  • 名称

    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的元素,因此要在元素中发送字符序列,您必须为{{ 1}},您可以使用以下任何 ocator策略

  • 名称

    ElementToBeClickable()
  • CssSelector

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...