为什么我在尝试获取包含每个结果的 link 的搜索结果面板时出现此错误?

Why i am getting this error when trying to get the search results panel that contains the link for each result?

我在尝试使用 Selenium 和 C# 开发这个简单的应用程序时遇到了很多错误

我只想制作一个应用程序(在windows应用程序或控制台应用程序中)打开浏览器,进入google页面,搜索“APPLES”并带出前5个结果,使用硒。

这是我正在使用的代码:

            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://google.com");
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            //IWebElement element = driver.FindElement(By.Id("gbqfq"));

            driver.FindElement(By.Name("q")).SendKeys("apples");


            //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: 'no such element: Unable to locate element: {"method":"css selector","selector":"#search"}

这应该可以满足您的需求:

        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("http://google.com");
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

        driver.FindElement(By.Name("q")).SendKeys("apples");
        
        // Click on the Search button
        driver.FindElement(By.Name("btnK")).Click();

        // Use a Css Selector to go down to the actual element, in this case <a>
        var results = driver.FindElements(By.CssSelector("#rso > div > div > div.r > a"));
        foreach (var item in results)
        {
            //Extract the page title and the url from the result
            var title = item.FindElement(By.TagName("h3")).Text;
            var url = item.GetProperty("href");
            Console.WriteLine($"{title} | {url}");
        }

简而言之,您遇到此错误是因为您没有在页面中搜索正确的元素。