简体   繁体   中英

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

I'm getting a lot of errors trying to do this simple app with Selenium and C#

I just want to make an application (in windows application or console application) that opens a browser, enter the google page, search for "APPLES" and bring the first 5 results, using selenium.

This is the code i'm using:

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

I'm getting a error that it can not find element search:

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

This should do what you need:

        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}");
        }

In short, you had this error because you were not searching for the proper element in the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM