Reputation: 311
How do I make sure that my selenium code scrapes all matching contents of my XPath?
Please help me with your ideas.
For example, these are my HTML Tags:
<tr class="1" role="r1">
<td class="c1">
<a href="www.google.com">
</a>
</td>
</tr>
<tr class="2" role="r2">
<td class="c2">
<a href="www.youtube.com">
</a>
</td>
</tr>
<tr class="3" role="c3">
<td class="c3">
<a href="www.facebook.com">
</a>
</td>
</tr>
I want my selenium code to fetch all links from href tag.
So, below is my XPath:
String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href");
System.out.println(links);
but it fetches only the first href output, i.e. www.google.com
.
The desired output is:
www.google.com
www.youtube.com
www.facebook.com
How can I achieve this?
Any array implementation would be better options?
Upvotes: 0
Views: 67
Reputation: 967
Try below code.
List<WebElement> links = driver.findElements(By.xpath("//tr/td/a"));
for(int i=0;i<links.size();i++){
System.out.println(links.get(i).getAttribute("href"));
}
Upvotes: 1
Reputation: 3384
Try Following code:
List<WebElement> elements= driver.findElements(By.xpath("//table/tbody/tr"));
int i =0 ;
while(i<elements.size()){
WebElement childElement = elements.get(i).findElement(By.cssSelector("a"));
System.out.println(childElement.getAttribute("href"));
i++;
}
Upvotes: 1