selenium-webdriverxpathwebdriverselector

XPath + Selector: Cannot find out a xPath to click when switching to another window


In my flow => I have switched to another window and cannot find out the xPath to click I have the following html => I tried some ways to click a tag [SerName] by xPath and Css Selector but they all do not work => It shows that this element cannot be find => Whether there is other way to resolve this problem. Btw, I also checked there is no iframe cover this tag

<div _ngcontent-blq-c9="" class="m-generalBtn m-generalBtn--sub m-generalBtn--interaction btn-past-news float-right"><a _ngcontent-blq-c9="" class="m-generalBtn__box m-generalBtn__box--sub modify-button__size -color-applied-rate m-btn__width" href="javascript:void(0)">SerName</a></div>

One of ways I tried but it did not work:

String termSegmentXpath = '//*[@id="tabUsageService"]/app-segment-details-usage-service/div/div/div[2]/div/a'
WebUI.delay(30)
WebDriver driver = DriverFactory.getWebDriver()
WebElement element = driver.findElement(By.xpath(termSegmentXpath))
JavascriptExecutor executor = ((driver) as JavascriptExecutor)
executor.executeScript('arguments[0].click()', element)

Solution

  • If you are certain that there is no IFRAME which is wrapping the desired element, then try to apply selenium's waits. Something like below:

    WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='SerName']")));
    element.click();
    

    Or try this:

    WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='SerName']")));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
    

    UPDATE: Since you edited the question and mentioned about switching to new window. Here is the code how you can go back to parent window.

    First, store the current window reference as below:

    String parentWindow= driver.getWindowHandle();
    

    Then, you may have switched to new window and performed actions. Once all actions are finished, then close that window with below code:

    driver.close();
    

    Now switch back to parent window:

    driver.switchTo().window(parentWindow);
    

    After switching back to parent window, try to click on the desired element.