c# - Selenium 不根据名称输入字符串?

标签 c# selenium testing selenium-webdriver automated-tests

我正在尝试使用 selenium 在 C# visual studio 中创建一些测试。当我运行测试时,谷歌浏览器导航到指定的网站,但是没有在用户名和密码字段中输入任何键/字符串...

这是为什么?我该如何解决?我如何创建一个测试,让用户输入正确的用户名和密码查询并单击提交表单。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;


namespace test
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            IWebDriver driver = new ChromeDriver("/Users/name/Desktop/test/");

            driver.Navigate().GoToUrl("http://newtours.demoaut.com/mercurywelcome.php");

            IWebElement username = driver.FindElement(By.Name("userName"));
            username.SendKeys("mercury");

            IWebElement password = driver.FindElement(By.Name("password"));
            password.SendKeys("mercury");

            var signIn = driver.FindElement(By.Name("login"));
            signIn.Submit();


        }
    }
}

最佳答案

页面加载需要一些时间。因此,请在导航到 URL 后添加一些等待时间。

在您的测试中添加以下 NuGet 包并修改如下代码

NuGet 包: DotNetSeleniumExtras.WaitHelpers

额外的命名空间声明,

using OpenQA.Selenium.Support.UI; //for the wait method
using SeleniumExtras.WaitHelpers;  //for the expected conditions method

工作代码:

    driver.Navigate().GoToUrl("http://newtours.demoaut.com/mercurywelcome.php");

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

    wait.Until(ExpectedConditions.TitleContains("Welcome"));//It will wait until the page load completion 

    IWebElement username = driver.FindElement(By.Name("userName"));
    username.SendKeys("mercury");

关于c# - Selenium 不根据名称输入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575957/

相关文章:

java - 驱动程序可执行文件的路径必须由 webdriver.gecko.driver 系统属性设置;

javascript - indexOf 不是 Firefox、Opera 中的函数,但在 IE 中有效,javascript 中的 indexOf 替代项用于测试字符串包含?

c# - 捕获 OutOfMemory 异常 C#

c# - 如何在 C# 中的 Dispose() 方法中处理托管资源?

c# - 警报处理 - Selenium WebDriver/Selenium RC 2.18.0 - 异常

java - JUnit : Run via eclipse and maven test. 速度差别很大,为什么?

ruby - 使用 Webrat 进行测试时如何处理 cookie?

关于委托(delegate)的 C# 问题

c# - ASP.NET 如何在 asp 按钮单击上填充 html 表

c# - 无法将 foreach 更改为 LINQ 语法