我在尝试用Selenium和C#做这个简单的应用程序时遇到了很多错误
我只想制作一个应用程序(在windows应用程序或控制台应用程序中(,打开浏览器,进入谷歌页面,搜索";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}");
}
简而言之,您出现此错误是因为您没有在页面中搜索正确的元素。