如何获取父元素文本并删除子元素文本selenium c#?

时间:2018-05-29 17:24:18

标签: javascript c# selenium selenium-webdriver xpath

我是自动化测试的新手,现在我正在使用selenium C#。 我有一个问题,我想从一个元素获取文本,但代码:

<div class="item">
Text1
<span>textdontwant</span>
</div>

和我的陈述

  

driver.FindElement(By.XPath( “// * [@ id中= 'contactList'] / DIV [1] / DIV / DIV [1] / DIV / DIV / DIV / DIV [2]”))。文本;

获取:

  

Text1textdontwant

我只需要父元素文本:

  

文本1

有人有解决方案吗? 非常感谢! 这里的HTML:

<div id="contactList" class="web z-data-list" tabindex="30" style="position: relative;">
   <div style="overflow: visible; height: 0px; width: 0px;">
      <div class="virtualized-scroll testing" style="height: 657px; width: 304px;">
         <div aria-label="grid" class="ReactVirtualized__Grid ReactVirtualized__List" role="grid" tabindex="-2" style="box-sizing: border-box; direction: ltr; height: 657px; position: absolute; width: 304px; will-change: auto; overflow: auto;">
            <div class="ReactVirtualized__Grid__innerScrollContainer" style="width: auto; height: 2198px; max-width: 304px; max-height: 2198px; overflow: hidden; position: relative;">
               <div style="height: 44px; left: 0px; position: absolute; top: 0px; width: 100%;">
                  <div class="contact-list__add flx flx-al-c nav-button_add_friend clickable  "><i class="fa fa-icon-add-friend contact-list__add__icon "></i><span class="contact_add_friend_item" data-translate-inner="STR_CONTACT_ADD_FRIEND">Thêm bạn</span></div>
               </div>


             <div style="height: 72px; left: 0px; position: absolute; top: 266px; width: 100%;">
   <div class="item minimized rel list-friend-conctact  ">
      <div class="avatar avatar--m list-friend-conctact__avatar">
         <div class="avatar-img  outline" style="background-image: url(&quot;//s120.avatar.talk.zdn.vn/4/8/c/f/27/120/c5ee9f2b5a5a87d227fe2faf376f2e2c.jpg&quot;);"></div>
      </div>
      <div class="list-friend-conctact friend_onlines_dot"></div>
      <div class="item-title list-friend-conctact__title has-status ">Text1
<span class="friend_online_status truncate" style="top: 0px; left: 3px;">Text dont want</span>
</div>
</div>


   </div>
</div>

1 个答案:

答案 0 :(得分:1)

根据您提供的用于提取文本 Text1 的HTML,您可以使用以下代码块:

IWebElement myElem = driver.FindElement(By.XPath("//div[@class='item-title list-friend-conctact__title has-status']"));
string myText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].firstChild.textContent;", myElem);