mjgirl
mjgirl

Reputation: 1234

Regular expressions and Selenium WebDriver xpath

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

Answers (2)

Santoshsarma
Santoshsarma

Reputation: 5667

  1. Try to get href attribute
  2. parse that string to get that 5 digit identifier
  3. use that identifier and construct your locator and click.
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

eugene.polschikov
eugene.polschikov

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

Related Questions