Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function for switching frames in python, selenium

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

like image 333
Andigger Avatar asked Feb 25 '15 15:02

Andigger


People also ask

How to switch frame in selenium?

Suppose if there are 100 frames in page, we can switch to frame in Selenium by using index. Switch to the frame by Name or ID: Name and ID are attributes for handling frames in Selenium through which we can switch to the iframe. Let's take an example to switch frame in Selenium displayed in the below image. Our requirement is to click the iframe.

How to move to a particular iframe in selenium Python?

Selenium Python API provides “switch_to.iframe (self, frame_reference)” method to move to a particular IFrame. the “<frame_reference>” parameter is the locator used to identify the IFrame. Let’s take a sample HTML code that will create multiple IFrames in the web page.

How to find element by X path using selenium?

All the frames interconnected. Then we perform these actions by selenium: First of all, switch to the default frame to the first frame. Go back to the default frame. Then switch to the 3rd frame. Then find element by x path.

How to switch frames within an <iframe>?

The website is Power BI based, so to switch within the <iframe> so you have to: Induce WebDriverWait for the desired frame to be available and switch to it. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium


1 Answers

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()
like image 186
ddavison Avatar answered Oct 18 '22 23:10

ddavison