1. 程式人生 > >webelement中的方法getText()和getAttribute(java.lang.String name)

webelement中的方法getText()和getAttribute(java.lang.String name)

getText(): 獲取元素的visible內嵌文字。

如csdn首頁中的連結<a class="left" target="_blank" href="http://www.csdn.net" onclick="LogClickCount(this,285);">首頁</a>

通過

        driver = new FirefoxDriver();
        url = "http://www.csdn.net/";
        driver.get(url);
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        String text = driver.findElement(By.xpath("//div[@class='csdn_pub_nav_bg']/div[1]/a[1]")).getText();

可取得文字“首頁”。

而對於頁面上輸入型別的元素(input,textarea等),則不能通過getText()獲取到相應的文字。如csdn首頁中搜索框中預設的“搜尋”二字。其標籤為<input id="srch1" class="search" type="text" onblur="if(this.value=='') this.value='搜尋'; this.style.color='#999'; return true;" onfocus="if(this.value=='搜尋') this.value='';this.style.color='#333'; return true;

" value="搜尋" name="passwordtwo" style="color: rgb(153, 153, 153);"/>

通過String errorValue = driver.findElement(By.xpath("//input[@class='search']")).getText();得到的值為空。此時應使用getAttribute()

getAttribute(String name):獲取元素中名為name的屬性的值。

通過String value = driver.findElement(By.xpath("//input[@class='search']")).getAttribute("value"); 即可獲取到值“搜尋

”。

通過String type = driver.findElement(By.xpath("//input[@class='search']")).getAttribute("type");則對應可獲得值“text”。