Home > Software engineering >  How to get the frame and switch to in Selenium Java?
How to get the frame and switch to in Selenium Java?

Time:11-18

I've been spending more than an hour to find similar cases but nothing helpful. I am new to Java and Selenium and only one member who develops the Selenium Automation script at the moment.

Okay, the target system's HTML code structure is as below.

code structure...

What I did to click on the element on the topframe is, for example, (simplified snippet);

Page page = new Page();

page.setTopFrame();
page.a_button.click();
class Page{
    @FindBy(id="a_button")
    public WebElement a_button;

    public void setTopFrame() {
        driver.switchTo().frame("topframe");
    }
}

But when I run this codes it returns "org.openqa.selenium.NoSuchElementException" Exception. I don't know what I am missing now. Any advice will be thankful.

--Edited-- Since I post this one, other Exception found which is "NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null.

The constructor in Page class should initialised with driver from main Test class. Be like.

Page page = new Page(driver);

And Page class has

Page class{
    WebDriver driver;

    public Page (WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }
...
}

CodePudding user response:

Maybe you are currently in another frame. So try:

public void setTopFrame() {
    driver.switchTo().defaultContent();
    driver.switchTo().frame("topframe");
}

CodePudding user response:

Page class{ WebDriver driver;

public Page (WebDriver driver){
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

... }

Thank you all read my question. I hope this answer help someone in trouble with same issue.

  • Related