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”。