Bhargav Raval Bhargav Raval - 5 months ago 17
Java Question

Unable to get text from html element for Selenium Java

I am using selenium with Java. I am unable to get text from html element that is a combobox. Every time I am getting blank text for the selected value in combobox.

Below is my html structure for combobox.

<ul id="servicetype-cave" class="z-combobox-content" style="height: auto; width: auto;">
<li id="zk_comp_140" class="z-comboitem">
<li id="zk_comp_141" class="z-comboitem">
<li id="zk_comp_142" class="z-comboitem">
<li id="zk_comp_143" class="z-comboitem">
<li id="zk_comp_144" class="z-comboitem z-comboitem-selected">
<span class="z-comboitem-image"/>
<span class="z-comboitem-text">Bill Grouping Service</span>
<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">

I have used below xpath for the element

@FindBy(xpath = "//ul[@id='servicetype-cave']/li[contains(@class,'z-comboitem-selected')]/span[@class='z-comboitem-text']")
public WebElement selectedServiceName;

public void selectService {
// Selecting an option from dropdown
WebElement tempEle = driver.findElement(By.xpath("(//div[@id='servicetype-pp']//span[2])[3]"));
String strtemp = selectedServiceName.getText();
System.out.println("Selected Service: " + strtemp);

Please help.



I'm suggesting you try using By.cssSelector() as below :-

WebElement el = driver.findElement(By.cssSelector("ul#servicetype-cave li.z-comboitem-selected span.z-comboitem-text"));


WebElement el = driver.findElement(By.cssSelector("ul#servicetype-cave li.z-comboitem.z-comboitem-selected span:nth-child(2)"));

Now use .getText() to getting the text as below :


If unfortunately .getText() does not work try using .getAttribute("textContent") as below :


or try using .getAttribute("innerHTML") as below :


Hope it works..:)