=================================================================================
============================================
"switch_to" has 7 foci which can be switched to:
i) alert ==>> See Example 1 below.
driver.switch_to.alert
ii) active_element
driver.switch_to.active_element
iii) default_content
driver.switch_to.default_content()
iv) frame
iv.a) The reason that it is named by frame(0), frame(1) and so on, is there can be many frames in a webpage.
iv.b) Basically, three ways can be used to switch over the elements and handle frames in Selenium (these methods can also be used to find iframe/frame in a webpage):
iv.b.1) By Index See Example 4 below.
driver.switch_to.frame(1)
iv.b.2) By Name or ID. See Example 3 and 5 below.
Note that when few of the frames share the same ID or name, then the ID or name cannot be used to find a specific frame.
driver.switch_to.frame('frame_name')
iv.b.3) By Web Element
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
v) new_window
vi) parent_frame
driver.switch_to.parent_frame()
vii) window ==>> See Example 2 below.
driver.switch_to.window('main')
Table 4482. switch.to.
============================================
Webpage code:
<div>
<frame id='Gooool'>
<button>Button in iframe</button>
</frame>
<button id='Dhg'>Button in main html (aka default content)</button>
</div>
Python code:
# switch to the iframe to click the 'Button in iframe'
driver.switch_to.frame('Gooool').contains('Button in iframe').click()
# switch back to the main html to click the 'Dhg' button
driver.switch_to.parent_frame().get('#Dhg').click()
============================================
Example 1: Switch_to function and alert popup window: code:
Output:
Find the alert1 button:
Alert popup window after "click()":
Printed output at the end of the process:
============================================
Example 2: window_handles and switch_to: code:
Steps to build the code:
Get the following after clicking inspect:
Righ click the line above:
Once the line below is performed, then the second window will open:
driver.find_element(By.XPATH, "//*[@id='Tabbed']/a/button").click()
Output:
After those lines below, then a window is closed as shown in the image below:
if driver.title == "Selenium":
driver.close() # Close the particular window
============================================
Example 3: switch_to.frame: code:
The code from webpage is:
Output (original in the webpage):
Output (after the Python code ran):
============================================
Example 4: Enter frame with frame index: code:
Frames on the webpage:
============================================
Example 5: Switch into frame layer by layer: Code:
Go into frame(0):
Go into frame(2):
Go to the checkbox:
:
Output:
|