getText(): 获取元素的visible内嵌文字。
如csdn首页中的链接<a class="left" target="_blank" href="http://www.youkuaiyun.com" onclick="LogClickCount(this,285);">首页</a>。
通过
driver = new FirefoxDriver();
url = "http://www.youkuaiyun.com/";
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”。

本文介绍如何使用Selenium WebDriver获取网页元素的可见文本及属性值,包括使用getText()方法获取链接文本和使用getAttribute()方法获取input元素的默认值。
2044

被折叠的 条评论
为什么被折叠?



