【问题标题】:NoSuchElementException in c# for google search box using selenium webdriverC# 中的 NoSuchElementException 用于使用 selenium webdriver 的谷歌搜索框
【发布时间】:2015-09-26 12:50:32
【问题描述】:

我正在尝试使用 selenium webdriver 自动执行简单的搜索。我的代码是在 IE 中启动 google.co.uk 页面,等到出现搜索框,找到搜索框并输入“比较市场”。但是,我不断从应用程序中收到 NoSuchElementException,即使我可以在页面上看到它。

我的代码:

class Program
{
    static void Main(string[] args)
    {
        string searchEngine = "www.google.co.uk";
        IWebDriver IEbrowser = new InternetExplorerDriver(@"C:\Drivers");
        IEbrowser.Url = searchEngine;
        WebDriverWait wait = new WebDriverWait(IEbrowser, TimeSpan.FromSeconds(25));
        IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
        {
            return d.FindElement(By.Name("q"));
        });
        
        var searchBox = IEbrowser.FindElement(By.Id("lst-ib"));
        searchBox.SendKeys("compare the market");
    }
}

错误信息:

WebDriver.dll 中出现“OpenQA.Selenium.NoSuchElementException”类型的异常,但未在用户代码中处理

附加信息:无法找到名称 == q 的元素

搜索框的 HTML 信息:

如果我尝试使用任何其他页面元素定位器(例如 Id),我会收到相同的错误消息。但这似乎只会在使用谷歌搜索页面时出错。

【问题讨论】:

  • 抱歉,HTML 信息:
  • 您应该编辑您的问题并从您的评论中添加 HTML 信息。它更有可能在问题中看到,并且在正确格式化时更容易阅读。谢谢!

标签: c# selenium selenium-webdriver


【解决方案1】:

你有点过度设计了这项任务。 :) 下面的代码工作正常。

string searchEngine = "www.google.co.uk";
IWebDriver IEbrowser = InternetExplorerDriver(@"C:\Drivers");
IEbrowser.Navigate().GoToUrl(searchEngine);
IEbrowser.FindElement(By.Id("lst-ib")).SendKeys("compare the market");

如果您想等待某个元素,可以使用ExpectedConditions 更简单的方法来执行此操作。请参阅下面的示例。阅读链接的文档,了解可以使用的其他可用条件。

WebDriverWait wait = new WebDriverWait(IEbrowser, TimeSpan.FromSeconds(25));
wait.Until(ExpectedConditions.ElementExists(By.Name("q")));

【讨论】:

  • 嗨,杰夫,你试过运行这段代码吗?它对你有用吗?我仍然收到相同的错误消息,当我添加等待条件时,应用程序等待 25 秒,然后给我一个超时错误。
  • 我使用 Firefox 驱动程序运行它,它运行良好。我没有安装IE驱动。一切都是最新的吗?您是否尝试过使用 Firefox 驱动程序?
  • 是的,它可以与 Firefox 一起使用,但不能与 IE 驱动程序一起使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多