如何在发送密钥selenium c#之前清除文本字段



我正在写一个简单的selenium测试,它发送了一个不正确的字符串,然后提交并返回并出错。然后我想发送一个字符串的信件,但这次用了正确的字符串,所以它被接受了。

我在测试中面临的问题是,第一组字符串已经在文本字段中,所以当我转到提交第二组字符串时,它会将其添加到已经提交的第一个字符串中。

所以我基本上需要做的是发送第一个字母串,然后需要清除文本字段,然后发送第二个字母串。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;
namespace Exercise1
{
class RunPath
{
static void Main()
{
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl("https://energy.gocompare.com/gas-electricity");
webDriver.Manage().Window.Maximize();

String title = webDriver.Title;
String expectedTitle = "Utilities from Go Compare";
if (title.Contains(expectedTitle))
{
Console.WriteLine("Tile is matching with expected value");
}
else
{
Console.WriteLine("Tile is matching with expected value");
}
webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();
webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN#");
webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

// I need a piece of code here so that before i send the second string of keys the text field is clear 
webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN");
webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

// webDriver.Quit();
}

}
}

添加一行代码以清除<input>字段,如下所示:

webDriver.FindElement(By.XPath(".//input[@type = 'text']")).Clear();
webDriver.FindElement(By.XPath(".//input[@type = 'text']")).SendKeys("W30PN");

理想情况下,当您在调用Navigate().GoToUrl()后处于新页面时,您应该诱导WebDriverWait使<input>元素可点击,并且您可以使用以下代码块:

IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath(".//input[@type='text']")));
element.Click();
element.Clear();
element.SendKeys("W30PN");

参考

你可以在中找到一些相关的讨论

  • clear((不清除带有selenium、python和firefox的文本框
  • 尝试通过Selenium清除文本时出现InvalidElementStateException
  • python selenium无法清除输入字段

clear命令可用于在文本字段中输入任何键之前清除元素

webDriver.FindElement(By.XPath("{Locator}")).Clear();
webDriver.FindElement(By.XPath("{Locator}")).SendKeys("{YOUR_KEY}");

用try-catch包围此语句,以便捕获和处理任何与硒相关的异常

在发送另一个密钥之前尝试此操作:

IWebElement textbox= driver.FindElement(By.XPath(".//input[@type = 'text']"));
textbox.SendKeys(OpenQA.Selenium.Keys.LeftShift + OpenQA.Selenium.Keys.Home)