无法使用ID或Name定位元素

时间:2019-04-21 08:05:19

标签: selenium-webdriver xpath css-selectors webdriver webdriverwait

HTML:

<input name="txtAnswer" type="text" maxlength="20" id="txtAnswer" class="box1">

代码试用:

driver.findElement(By.xpath("//table[@id='tblSecurityAnswer']//tbody//tr[2]//td[2]//input[@id='txtAnswer']")).sendKeys("green");

还有:

driver.findElement(By.cssSelector("//tr:nth-child(1) > td > table > tbody >
    // tr:nth-child(2) > td:nth-child(2)"));

public static void main(String[] args) throws InterruptedException {
    WebDriver driver;

    // IE webdriver
    // System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
    // driver = new InternetExplorerDriver();

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    driver = new ChromeDriver();

    // Maximize the browser window
    driver.manage().window().maximize();

    // navigate to specified url
    driver.get("http://dxbqcapp01/molforms/login.aspx");

    driver.findElement(By.id("txtUserName")).sendKeys("MS200963915");
    driver.findElement(By.id("txtPassword")).sendKeys("test@123");
    driver.findElement(By.xpath("//input[@type='submit' and @value='Submit']")).sendKeys(Keys.ENTER);
    driver.findElement(By.id("txtAnswer")).sendKeys("green");

1 个答案:

答案 0 :(得分:-1)

错误堆栈跟踪可以帮助我们以更好的方式调试问题。但是,要将字符序列发送到所需元素,您必须诱使 WebDriverWait 使元素可点击,并且可以使用以下任意一种Locator Strategies

  • cssSelector

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.box1#txtAnswer"))).sendKeys("green");
    
  • xpath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='box1' and @id='txtAnswer']"))).sendKeys("green");