问题描述
为什么我会收到此错误?:
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}},您可以使用以下任何
-
名称:
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");