簡體   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