如何通过使用类获取输入值?

时间:2016-07-11 12:40:27

标签: java eclipse selenium-webdriver

我正在使用以下代码

WebElement inputele = driver.findElement(By.className("class_name"));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);

但值为empty。 HTML在下面。

<div id="main">
   <div id="hiddenresult">
      <div class="tech-blog-list">
         <label for="Question">1st Question</label>
         <input id="txt60" class="form-control" type="text" value="sddf sd sdfsdf sdf sdfsdf sdfsdfsd fsd" />
      </div>
   </div>
   <div class="pagination_main pull-left">
      <div id="Pagination">
         <div class="pagination">
            <a class="previous" onclick="PreviousBtnClickEvent();" href="javascript:void(0)">Previous</a>
            <a id="pg59" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">1</a>
            <a id="pg41" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">2</a>
            <a id="pg40" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textarea">3</a>
            <a id="pg60" class="ep current" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">4</a>
         </div>
      </div>
   </div>
</div>

2 个答案:

答案 0 :(得分:0)

尝试使用WebDriverWait等待元素在页面上完全加载并显示如下: -

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement inputele= wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("class_name")));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);

注意: - By.className("class_name")会为该元素提供哪个类属性等于class_name。确保要定位的元素是class属性等于class_name的唯一元素,否则它将给出条件为true的第一个元素。

希望它能起作用.. :)

答案 1 :(得分:0)

Looks like your code is pretty close but you have the wrong class name? In your code above, you had "class_name" instead of "form-control". I'm assuming that was some sample code and not the actual code you are using? There is only one INPUT in the HTML and the code below should work. It also has an ID so that should be more specific in case there are more than one INPUTs on the page.

WebElement inputele= driver.findElement(By.className("form-control"));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);