简体   繁体   中英

Web Element is not identified by Xpath containing a text for Selenium WebDriver Java

I am using Selenium WebDriver with Java.

Below is my html code:

<div id="servicetype-pp" class="z-combobox-popup " style="display: none; width: auto;">
    <ul id="servicetype-cave" class="z-combobox-content">
        <li id="zk_comp_140" class="z-comboitem">
        <li id="zk_comp_141" class="z-comboitem">
            <span class="z-comboitem-image"></span>
            <span class="z-comboitem-text">Bill Generation Service</span>
        </li>
        <li id="zk_comp_142" class="z-comboitem">
        <li id="zk_comp_143" class="z-comboitem">
        <li id="zk_comp_144" class="z-comboitem">
        <li id="zk_comp_145" class="z-comboitem">
        <li id="zk_comp_146" class="z-comboitem">
        <li id="zk_comp_147" class="z-comboitem">
        <li id="zk_comp_148" class="z-comboitem">
        <li id="zk_comp_149" class="z-comboitem">
        <li id="zk_comp_150" class="z-comboitem">
    </ul>
</div>

I have defined a WebElement by xpath containing a particular text.

//div[@id='servicetype-pp']//span[contains(text(),'Bill Generation Service')]

It is not working. But, when I search with a single word, without any space, it is working fine.

//div[@id='servicetype-pp']//span[contains(text(),'Bill')] or
//div[@id='servicetype-pp']//span[contains(text(),'Generation')] or 
//div[@id='servicetype-pp']//span[contains(text(),'Service')]

It seems it is an issue with space.

Please help.

TIA.

您可以尝试使用normalize-space()

//div[@id='servicetype-pp']//span[contains(text()[normalize-space()], 'Bill Generation Service')]

Actually your <div id="servicetype-pp" class="z-combobox-popup " style="display: none; width: auto;"> looks as invisible that's why you are not able to interact with the element, try as below :-

WebElement el = driver.findElement(By.id("servicetype-pp"));
el = (WebElement)((JavascriptExecutor)driver).executeScript("arguments[0].style.display = 'block';return arguments[0]", el);

//Now you can find your desire element
WebElement spanElement = el.findElement(".//span[contains(text(),'Bill Generation Service')]");

//Now do your further steps with this element

Edited :- If you are getting NuSuchElementExcpetion that means visibility is not the issue, It might be possible that this element is inside a frame or iframe . If it is, you need to switch that frame or iframe before finding element as below :

 driver.switchTo().frame("frame name or id");

// Now go to find element 
WebElement spanElement = driver.findElement(".//span[contains(text(),'Bill Generation Service')]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM