繁体   English   中英

Selenium WebDriver 中的 getText() 和 getAttribute() 有什么区别?

[英]What is the difference between getText() and getAttribute() in Selenium WebDriver?

两者都用于获取标签之间的 WebElement 值。

我的假设正确吗? 如有错,请详述。

  <input attr1='a' attr2='b' attr3='c'>foo</input>

getAttribute(attr1)你得到 'a'

getAttribute(attr2)你得到 'b'

getAttribute(attr3)你得到'c'

没有参数的getText()你只能得到 'foo'

getAttribute() -> 它获取包含 HTML 标签中任何属性之一的文本。 假设有一个 HTML 标签,如

<input name="Name Locator" value="selenium">Hello</input>

现在 getAttribute() 获取 'value' 属性的数据,即“Selenium”。

返回:

如果未设置该值,则该属性的当前值或 null。

driver.findElement(By.name("Name Locator")).getAttribute("value")  //

字段值由 getAttribute("value") Selenium WebDriver 预定义方法检索并分配给 String 对象。

getText() -> 提供 WebElement 的 innerText。 获取此元素的可见(即不被 CSS 隐藏)innerText,包括子元素,没有任何前导或尾随空格。

返回:

此元素的innerText。

driver.findElement(By.name("Name Locator")).getText();

“你好”会出现

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

在上面的 html 标签中,我们有不同的属性,如srcaltwidthheight

如果你想从上面的 html 标签中获取任何属性值,你必须在getAttribute()方法中传递属性值

句法:

getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104 

getText():获取该元素的可见(即不被CSS隐藏)innerText,包括子元素,没有任何前导或尾随空格。

getAttribute(String attrName):获取元素的给定属性的值。 将返回当前值,即使在页面加载后已修改。 更确切地说,此方法将返回给定属性的值,除非该属性不存在,在这种情况下,将返回具有相同名称的属性的值(例如,对于 textarea 元素的“value”属性)。 如果没有设置任何值,则返回 null。 “样式”属性被尽可能地转换为带有尾随分号的文本表示。 以下被视为“布尔”属性,并将返回“true”或空值:async、autofocus、autoplay、checked、compact、complete、controls、declare、defaultchecked、defaultselected、defer、disabled、draggable、end、formnovalidate , 隐藏, 不确定, iscontenteditable, ismap, itemscope, 循环, 多个, 静音, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped,无缝, 搜索, 选择, 拼写检查, truespeed , willvalidate 最后,按预期评估以下通常错误大写的属性/属性名称:“class”“readonly”

getText()返回元素的可见文本。

getAttribute(String attrName)返回作为参数传递的属性值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM