首页 文章

无法使用Selenium获取元素的文本

提问于
浏览
1

我试图使用WebDriver.getText()方法从元素中获取文本,但我总是得到一个空字符串 .

以下是详细信息:

环境:网络浏览器: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")以及this answer中建议的几个java脚本(说实话我不理解它们但我还是尝试过它们)并且我没有找到成功 .

我真的很感激任何帮助 .

谢谢

3 回答

  • 0

    试试以下代码:

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

    尝试单击“选择”下拉菜单并尝试获取注意:确保您的框架正确

  • 0

    首先打开下拉列表,找到父WebElement并在父WebElement中找到WebElement profileName 并使用 getText() 方法 .

    试试以下代码:

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

相关问题