如何通过硒和C#调用sendkeys()到输入元素



基本上,我想将密钥发送到输入元素。我尝试使用SendKeys()方法,但它没有发送我使用的值,而是使用输入框的先前值属性。此外,使用SendKeys()或使用ExecuteScript()方法不会更改输入元素的值属性。以下是我尝试过的代码件,并且无法正常工作:

// Wait for zipcode input box
Utilities.WaitUntilElementIsPresent(driver, By.CssSelector("input#fad-dealer-searchbar-search-textbox"));
// click to go to the us site
var zipcodeInput = driver.FindElement(By.CssSelector("input#fad-dealer-searchbar-search-textbox"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
zipcodeInput.Clear();
zipcodeInput.Click();
//js.ExecuteScript("arguments[0].setAttribute('value', '11361')", zipcodeInput);
//js.ExecuteScript("document.getElementById('fad-dealer-searchbar-search-textbox').setAttribute('value', " + zipcode + ")");
//js.ExecuteScript("document.getElementById('fad-dealer-searchbar-search-textbox').value=11361");
//js.ExecuteScript("document.getElementById('fad-dealer-searchbar-search-textbox').innerHTML = 11361;");
zipcodeInput.SendKeys(zipcode);
zipcodeInput.Submit();
zipcodeInput.SendKeys(Keys.Enter);

这是我需要输入文本的输入元素:

<div class="sdp-form-text-box-text-box-container search-textbox">      
  <input type="number" autocomplete="off" value="00002" data-validation-state="success" aria-invalid="false" aria-required="true" class="sdp-form-text-box-text-box gcss-button-align-left" id="fad-dealer-searchbar-search-textbox" maxlength="5" name="searchTextBoxValue" pattern="d*" placeholder="Enter ZIP Code" required="" role="search">                                           
</div>

如果您需要检查克莱斯勒,这是我要爬的网站。我希望我已经正确解释了我的问题。任何帮助都将不胜感激。

在函数" waituntilelelementispresent"中,您需要检查在WebDriver上应用的预期条件。以下是类似的代码。您可以使用" elementisvisible"或" elementTobeClickable"。

public static IWebElement WaitUntilElementIsPresent(this IWebDriver driver,By elementLocator, int timeout = 10)
    {
        try
        {
            var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
            return wait.Until(ExpectedConditions.ElementIsVisible(elementLocator));
        }
        catch (NoSuchElementException)
        {
            Console.WriteLine("Element with locator: '" + elementLocator + "' was not found.");
            throw;
        }
    }

要调用 SendKeys(),您需要诱导 webdriverwait 与预期的条件作为元素tobeclickable,您可以使用以下任何解决方案:

  • CssSelector

    var zipcodeInput = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("label.gcss-sr-only[for^='change-zip__input-field-']")));
    zipcodeInput.Click();
    zipcodeInput.Clear();
    zipcodeInput.SendKeys(zipcode);
    
  • XPath

    var zipcodeInput = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//label[@class='gcss-sr-only' and starts-with(@for, 'change-zip__input-field-')]")));
    zipcodeInput.Click();
    zipcodeInput.Clear();
    zipcodeInput.SendKeys(zipcode);
    

注意

  • 确保 zipcode 仅由数字组成。
  • 确保 zipcode 最大长度是 5 仅数字。

最新更新