26

I'm looking for a function that makes it easier to switch between two frames. Right now, every time I need to switch between frames, I'm doing this by the following code:

driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='nav']"))

driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='content']"))

My goal is to get a function that takes an argument just to change nav or content since the rest is basically the same.

What I've already tried is:

def frame_switch(content_or_nav):
x = str(frame[name=str(content_or_nav)] #"frame[name='content_or_nav']"
driver.switch_to.frame(driver.find_element_by_css_selector(x))

But it gives me an error

 x = str(frame[name=str(content_or_nav)]
                  ^

SyntaxError: invalid syntax

1 Answer 1

73

The way this is written, it's trying to parse CSS code as Python code. You don't want that.

This function is suitable:

def frame_switch(css_selector):
  driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))

If you are just trying to switch to the frame based on the name attribute, then you can use this:

def frame_switch(name):
  driver.switch_to.frame(driver.find_element_by_name(name))

To switch back to the main window, you can use

driver.switch_to.default_content()
Sign up to request clarification or add additional context in comments.

5 Comments

you're very welcome! go ahead and click accept (the checkmark), and optionally, give an upvote if helped :)
can't upvote already because I need 15 reputations first, else I would ;)
May it be complete with command to switch back to the main window?
yes @NamGVU, there is! driver.switch_to.default_content()
It worked. From the web that I did automation testing has the hidden frame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.