问题描述
尝试使用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}");
}
简而言之,您遇到此错误是因为您没有在页面中搜索适当的元素。