Reputation: 29
I have a little question about selenium in java.
In my program I have a lot of href with:
/cms/shops/edit?id=xxx
<a href="/cms/shops/edit?id=736" class="btn btn-sm btn-primary">Edit</a>
<a href="/cms/shops/edit?id=321" class="btn btn-sm btn-primary">Edit</a>
<a href="/cms/shops/edit?id=123" class="btn btn-sm btn-primary">Edit</a>
How can I get only xxx(id)
value in Selenium (Java) and add to array for example??
Upvotes: 0
Views: 310
Reputation: 193058
As per the HTML
you shared to print only xxx(id) value you can use the following code block :
List<WebElement> linkList = driver.findElements(By.cssSelector("a.btn.btn-sm.btn-primary[href^='/cms/shops/edit?id']"));
List<Integer> idListFromLink = new ArrayList<Integer>();
for(WebElement link : linkList){
String my_href = link.getAttribute("href");
String[] parts = my_href.split("=");
idListFromLink.add(Integer.parseInt(parts[1]));
}
System.out.println(idListFromLink);
Upvotes: 0
Reputation: 2799
Code Snipppet:
- ArrayList
implementation:
List<WebElement> linkList = driver.findElements(By.cssSelector("a[class^='btn btn-sm']"));
List<Integer> idListFromLink = new ArrayList<Integer>();
for(WebElement link : linkList){
String [] temp = link.getAttribute("href").split("=");
int id = Integer.valueOf(temp[temp.length - 1]);
idListFromLink.add(id);
}
- Array
implementation:
List<WebElement> linkList = driver.findElements(By.cssSelector("a[class^='btn btn-sm']"));
int listSize = linkList.size();
int [] idListFromLink = new int[listSize];
for(int i = 0; i < listSize; i++){
String [] temp = linkList.get(i).getAttribute("href").split("="); //split the href value using delimeter '='
int id = Integer.valueOf(temp[temp.length - 1]); //get the last item
idListFromLink[i] = id;
}
Upvotes: 1