如何解决无法使用Selenium和C#在Google主页上找到搜索框元素
为什么我会收到此错误?:
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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。