gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:28:53 24 4
gpt4 key购买 nike

我是自动化测试的新手,现在我正在使用 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]")).Text;

获取:

Text1textdontwant

我只需要父元素文本是:

Text1

谁有解决办法?非常感谢!这里是 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>

最佳答案

根据您提供的用于提取文本 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);

关于javascript - 如何获取父元素文本并删除子元素文本 selenium c#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50589794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com