Reputation: 1234
How can I fix this code to work?
public void check(WebDriver driver) {
driver.findElement(By.xpath("//a[matches(@href,'/staff/transcript/\\d{5}//.pdf')]")).click();
}
I must find a link where 5-digit indentifier varies.
Upvotes: 0
Views: 8916
Reputation: 5667
String href=driver.findElement(By.xpath("//a[contains(@href,'/staff/transcript/')][contains(@href,'.pdf')]")).getAttribute("href"); String identifier=href.substring(href.lastIndexOf("/")+1,href.indexOf(".")); driver.findElement(By.xpath("//a[matches(@href,'/staff/transcript/"+identifier+"//.pdf')]")).click();
Upvotes: 1
Reputation: 7339
one possible solution to your problem: using js iterate through all tags and find first which corresponds to your regex.
pubic String getLocatorByRegExp(){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var regex = /^\d{5}$/");
stringBuilder.append("var x=document.getElementsByTagName('a');");
stringBuilder.append("for(var t = 0; t <x.length; t++){if(regex.test(parseInt(x[t].text()))) return x[t].text().toString();} ");
String res= (String) js.executeScript(stringBuilder.toString());
return res;
}
String properLinkText = getLocatorByRegExp();
driver.findElement(By.xpath(//a[contains(text(),properLinkText)])).click()
Quite complicated approach. But it seems to me that it is possible to find simplier solution. Is it 5-digit indentifier unique on the page ( i mean only one element on the page ?) If so, it is easy to find css locator or xpath to this element. Provide please some piece of your html and point out element you need to click on.
Upvotes: 0