簡體   English   中英

無法使用Selenium獲取元素的文本

[英]Not able to get text for an element using Selenium

我正在嘗試使用WebDriver.getText()方法從元素中獲取文本,但是我總是得到一個空字符串。

以下是詳細信息:

環境:Web瀏覽器:Chrome版本:48.0 Chrome驅動程序版本:2.20

應用程序:在我的主頁上,單擊菜單選項,該選項在屏幕上創建一個下拉菜單,而我試圖從中獲取文本的元素是此下拉菜單中的元素之一。

DOM:

<div class="settingInfo ng-scope" ng-if="showSettings">
  <div class="settingsDropDown">
    <ul class="drop-down-menus">
      <li>some data</li>
    <div id="showProfile" data="$root.userGroup.getUserProfiles()" is-overlay-required="true" is-profile-option-required="true" extra-label="true" profile-ordering="true" class="ng-isolate-scope">
      <ul class="profileList">
          <!-- ngRepeat: profile in data | filter: { userType : 'RegularUser'} | orderBy : 'displayName' : profileOrdering --><li ng-repeat="profile in data | filter: { userType : 'RegularUser'} | orderBy : 'displayName' : profileOrdering" ng-click="togglePanel($index, profile);" class="profile-titles ng-scope setting-dropDown-firstP" id="selectProfile_0" ng-class="{'activeProfile':(profile.isActive &amp;&amp; !showProfileOption),'clickedProfile':($index == currentIndex &amp;&amp; showProfileOption),'setting-dropDown-firstP':(($index == 0) &amp;&amp; (data.length <= 3))}">
                <div class="profileCircle ng-binding">T</div>
                <div class="profileName ng-binding">Test Profile</div>
          <li>
        </ul>
      </div>

我有興趣從上述代碼中獲取文本“ Test Profile”。

XPATH:

我正在使用以下XPATH來引用元素:

//div[@id="showProfile"]//li[@id="selectProfile_0"]/div[contains(@class, "profileName")]

chrome中的XPath Helper擴展告訴我xpath是唯一的,但是當我嘗試對此xpath標識的元素執行getText時,會得到一個空字符串。

Java代碼:

List<WebElement>list  = getProfileList();  //this function checks if element is visible and if it is visible it adds it in to the list and returns it.
for(Webelement e : list)
{
    System.out.println(e.getText());
}

除此之外,我嘗試了getAttribute(“ innerHTML”),getAttribute(“ innerText”)和此答案中建議的一些Java腳本(說實話,我不理解它們,但我仍然嘗試過),但沒有找到成功。

我真的很感激任何幫助。

謝謝

試試下面的代碼:

WebElement element = driver.findElement(By.xpath("//div[contains(text(),'Test Profile')]"));
String text = element.getText();

嘗試單擊“選擇”下拉列表,然后嘗試獲取注釋:確保您位於正確的框架中

首先打開下拉菜單,找到父WebElement,然后在父WebElement中找到WebElement profileName並使用getText()方法。

試試以下代碼:

WebElement parentElement = driver.findElement(By.className("settingsDropDown")); 
WebElement profileName = parentElement.findElement(By.className("profileName ));
String text = profileName.getText();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM