我正在尝试使用 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/