Reputation: 2689
I am new to selenium and I am writing tests for an existing web app. I am trying to select an option from a dynamically generated list. The following HTML is an example of the list:
<table id="selectChannelForm">
<tbody id=""></tbody>
<tbody id="">
<tr rowtype="container">
<td colspan="3" class="second">
<ul>
<li>
<a href="selectChannel.php?selectedChannelId=103">
<span>Sales Channel</span>
</a>
</li>
<li>
<a href="selectChannel.php?selectedChannelId=108">
<span>Demo channel</span>
</a>
</li>
<li>
<a href="selectChannel.php?selectedChannelId=112">
<span>Finance Channel</span>
</a>
</li>
<li>
<a href="selectChannel.php?selectedChannelId=121">
<span>HR Channel</span>
</a>
</li>
<li>
<a href="selectChannel.php?selectedChannelId=156">
<span>Management Channel</span>
</a>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
I need to select one of these channels for a test, but the problem is that I can't do a direct CSS or XPath reference because both the tbody and the channel list changes based on certain criteria. How would I use either the channelId or span text to select the correct option? The following is a direct CSS reference to the fourth option.
WebElement channelBtn = driver.findElement(By.cssSelector("#selectChannelForm > tbody:nth-child(2) > tr > td > ul > li:nth-child(4) > a"));
Is it at all possible to put some logic in these statements? Or some other means of selecting an nth-child
?
Upvotes: 1
Views: 5359
Reputation: 4424
You can also try the below way using CSS selector:
WebElement channelBtn = driver.findElement(By.cssSelector("td.second:nth-of-type(1) li:nth-of-type(4) span"));
This will navigate to the span tag under 4th li tag of first td element with class 'second' in the webpage, i.e.,"HR Channel"
Upvotes: 0
Reputation: 2689
So after a lot of searching I have come up with the following solution for a CSS based approach. Works perfectly
List<WebElement> channels = driver.findElements(By.tagName("span"));
for(WebElement channel : channels){
String selectedChannel = channel.getText();
if (selectedChannel.equalsIgnoreCase(channelId)){
channel.click();
break;
}
}
Upvotes: 0
Reputation: 1956
To use 'Channel ID'
xpath = //a[@href='selectChannel.php?selectedChannelId=108']
css = a[href='selectChannel.php?selectedChannelId=108']
Second to use 'span text' to select the correct option you can use
xpath = //span[contains(text(),'Demo channel')]
css = span:contains('Demo channel')
Upvotes: 1
Reputation: 8264
You can use an xpath like this to find the link with the channel you're looking for:
//a[@href='selectChannel.php?selectedChannelId=108']
Then, just replace 108 with whatever channel number you need.
Upvotes: 2