StatusQuo
StatusQuo

Reputation: 1436

selecting elements in WebDriver using xpath

How do I select only the parent span webelement and not the child?

List summaryLinks = summary.findElements(By.xpath(""));

My HTML code :

<li>
<div class="mod-indent mod-indent-2">
<a href="http://mysite.com">
<img class="activityicon" alt="URL" src="http://mysite.com">
<span class="instancename">LinkText <span class="accesshide "> URL</span></span>
</a>
</div>
</li>

I tried the following xpaths but didn't work
.//div[@class='mod-indent mod-indent-2']/a/span[@class='instancename']

.//div[@class='mod-indent mod-indent-2']/a/span[1]

.//div[@class='mod-indent mod-indent-2']/a/span/.

.//div[@class='mod-indent mod-indent-2']/a/span [position() =1]

.//div[@class='mod-indent mod-indent-2']/a/span/span [position() =1]

Upvotes: 0

Views: 11100

Answers (2)

StatusQuo
StatusQuo

Reputation: 1436

WebDriver code:

List <WebElement> summaryLinks = 
summary.findElements(By.cssSelector("span.instancename")); 
List <String> links = new ArrayList <String> (); 
for (int i=0; i<summaryLinks.size(); i++){ 
        WebElement element =summaryLinks.get(i); 
         if (element.isDisplayed() && element.isEnabled()){ 
         String str  = element.getText(); 
         links.add(str);}} 
System.out.println(links); 

results in the following Output:

[Announcements 
Forum, Student Lounge 
Forum, Welcome 
Page, Instructor Bio 
URL, Course Schedule 
Page] 

Now, when I return links.size() it returns the correct number of elements (i.e. includes only parent span).

I'm not sure whether this is just a print return issue. I tried trim(), toString() before adding the return of getText() into links but its results are the same.

Upvotes: 0

Arran
Arran

Reputation: 25056

Multiple ways, but just a few:

By.XPath("//div[contains(@class, 'mod-indent-2')]/descendant::span[@class='instancename']");

By.XPath("//span[@class='instancename']");

By.XPath("//span[@class='accesshide ']/..");

By.ClassName("instancename");

By.CssSelector("span.instancename");

By.XPath("//span[text()='Link Text']");

Upvotes: 5

Related Questions