如何使用Selenium C#

时间:2019-03-28 06:43:43

标签: c# selenium xpath css-selectors webdriverwait

我知道这可能是一个重复的问题,但是我尝试了各种方法来解决这个问题,但无法解决这种情况

enter image description here enter image description here

从网站复制的HTML代码

<input name="ctl00$TabContainer1$tpMain$ContentPlaceHolder1$Ins$txtDob" type="text" value="(dd/mm/yyyy)" maxlength="10" id="ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob" onselect="javascript:if(this.value=='(dd/mm/yyyy)') this.value='';this.style.color='';" onblur="javascript:InputValidation(this,'Date','Date of Birth','(dd/mm/yyyy)');" onclick="javascript:if(this.value=='(dd/mm/yyyy)') this.value='';this.style.color='';" onkeydown="return autodate(this)" onchange="javascript:CheckChanges();" onkeypress="return onlyNumbersWithForwardslash();" style="width:90%;" tabindex="0">

我的代码是这样

string dob = startDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
string[] array = dob.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
char[] Chararray = string.Join(string.Empty, array).ToCharArray();

IWebElement DobElement = driver.FindElement(By.XPath("//*[@id='ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob']")); // .Id("ctl00_TabContainer1_tpMain_ContentPlaceHolder1_Ins_txtDob"));
    DobElement.Clear();

    foreach (char s in Chararray)
    {
         int num = Int32.Parse(s.ToString());
         DobElement.SendKeys(""+num);
    }

感谢您的帮助,以将数字输入文本框

1 个答案:

答案 0 :(得分:2)

由于所需元素是启用了JavaScript的元素,因此需要诱使 WebDriverWait 以使所需元素可点击,并且可以使用以下任意一种方法解决方案:

  • CssSelector

    IWebElement DobElement = driver.FindElement(By.CssSelector("input[id$='_Ins_txtDob'][name$='txtDob'][onblur*='InputValidation')]"));
    DobElement.Click();
    DobElement.Clear();
    
  • XPath

    IWebElement DobElement = driver.FindElement(By.XPath("//input[contains(@id, '_Ins_txtDob') and contains(@name, 'txtDob')][contains(@onblur, 'InputValidation')]"));
    DobElement.Click();
    DobElement.Clear();