Abhishek
Abhishek

Reputation: 1

Selenium Xpath combine

It seems there is something terribly wrong with the X-path. I am trying to concatenate the X-path inside loop but the result is an error message. Please help me out of this

WebElement e=driver.findElement(By.xpath("//tr[2]//tr//table/tbody/tr[1]/td/table[contains(@id,'fs')]/tbody")); 

            for (int i=1; i<numRows; i++) 
            {
                    Row row = sheet.getRow(i);
                    if (row != null){
                        for (int j=0; j<numCols; j++){
                            if (row.getCell(j) != null){
                                if(row.getCell(j).getStringCellValue() != null) {

                                    if(j==0 && !details[i][j].equalsIgnoreCase("XXX"))
                                    {
                                    WebElement style=driver.findElement(By.xpath(e+"/tr["+k+"]/td[1]/input"));
                                    style.sendKeys(details[i][j]);
                                    style.sendKeys(Keys.TAB);
                                    ReusableMethods.expliwait(driver);
                                    }

The Below error message is displayed in Eclipse console org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression [[ChromeDriver: chrome on XP (51c2231ca09b3dab440d7c6ebce322de)] -> xpath: //tr[2]//tr//table/tbody/tr[1]/td/table[contains(@id,'fs')]/tbody]/tr[0]/td[1]/input

I have marked the wrong expression in BOLD in the above result. I am not sure why "]" is being added while concatenating X-path

Upvotes: 0

Views: 1026

Answers (1)

Andersson
Andersson

Reputation: 52675

If you want to match element with XPath like //tr[2]//tr//table/tbody/tr[1]/td/table[contains(@id,'fs')]/tbody + /tr["+k+"]/td[1]/input you might need to use below syntax:

WebElement e=driver.findElement(By.xpath("//tr[2]//tr//table/tbody/tr[1]/td/table[contains(@id,'fs')]/tbody"));
WebElement style=e.findElement(By.xpath("./tr["+k+"]/td[1]/input"));

Also I suggest you to avoid this kind of XPath and use simple relative XPath expressions instead

Upvotes: 1

Related Questions