How to use switch_to_tab method in SeleniumBase

Best Python code snippet using SeleniumBase

Browser.py

Source:Browser.py Github

copy

Full Screen

...32 if adblock:33 time.sleep(10)34 self.close_tab("getadblock.com_1", switch_to_tab_key=(set(self.tabs.keys()) - {"getadblock.com_1"}).pop()) #have to provide the only key left in the dictionary35 time.sleep(sleep_time)36 def switch_to_tab(self, tab_key):37 if tab_key not in self.tabs.keys(): raise ValueError("tab_key not in self.tabs.keys().")38 if tab_key != self.current_tab_key:39 self.chrome.switch_to.window(self.tabs[tab_key]['handle'])40 self.current_tab_key = tab_key41 else:42 print("This tab is already selected.")43 def go_to_link(self, target_link, tab_key, page_load_time = 5,element_load=dict()): #element_load - ?44 if tab_key not in self.tabs.keys(): raise ValueError("tab_key not in self.tabs.keys().")45 if (tab_key != self.current_tab_key): self.chrome.switch_to_tab(tab_key)46 self.chrome.get(target_link)47 48 if (element_load == {}):49 time.sleep(page_load_time)50 self.modify_tabkey_value(tab_key, target_link, switch_to_tab=True) #switch_to_tab=TRUE in order to update self.current_tab_key51 # #could cause issues when the link redirects to another website52 else:53 try:54 WebDriverWait(self.chrome,element_load["time"]).until(EC.presence_of_element_located( (By.XPATH, element_load["element_xpath"])))55 self.modify_tabkey_value(tab_key, target_link, switch_to_tab=True) #switch_to_tab=TRUE in order to update self.current_tab_key56 except TimeoutException:57 self.chrome.get(self.tabs[tab_key]['link']) #back to original link58 print("Timed out while waiting for element to show up - method go_to_link()")59 except NoSuchElementException:60 self.chrome.get(self.tabs[tab_key]['link']) #back to original link61 print("Element was not found - method go_to_link()")62 except KeyError:63 self.chrome.get(self.tabs[tab_key]['link']) #back to original link64 print(element_load)65 print("this is element_load dictionary")66 print("Dictionary keys are not found, correct them - method go_to_link()")67 68 def open_new_tab(self, tab_link="http://www.google.com", switch_to_new_tab=True):69 self.chrome.execute_script('''window.open("'''+tab_link+'''", "_blank");''')70 time.sleep(5) #wait for page to open71 self.add_tab_to_tabs(tab_link, self.chrome.window_handles[-1], switch_to_new_tab) #last element in a list because the newly opened tab will always be last72 73 def close_tab(self,close_tab_key,switch_to_tab_key = None):74 #switch_to_tab_key provides a tab to switch to in case we want to close current tab; if None is passed it means we want self.current_tab_key75 if switch_to_tab_key == None: switch_to_tab_key = self.current_tab_key76 if (close_tab_key and switch_to_tab_key) in self.tabs:77 if close_tab_key == switch_to_tab_key: #only 1 tab should be opened78 if len(self.tabs.keys()) == 1:79 self.chrome.close() #close the only tab left80 self.tabs.pop(close_tab_key)81 self.current_tab_key = ""82 print('No tabs opened.')83 else: #can't switch to a tab that was just closed84 raise ValueError('Provide appropriate (not close_tab_key) switch_to_tab_key.')85 else: #more than 1 tab opened overall86 if close_tab_key != self.current_tab_key: self.switch_to_tab(close_tab_key)87 self.chrome.close() #don't know which tab browser will switch to after calling close(), so we will use switch_to 2 lines below88 self.tabs.pop(close_tab_key)89 self.switch_to_tab(switch_to_tab_key)90 else:91 raise NoSuchWindowError("Tab not found, either close_tab_key or switch_to_tab_key.")92 93 def add_tab_to_tabs(self, tab_link, tab_handle, switch_to_tab=True): #adds tab to list of tabs and optionally switch to a newly made tab; tab_link made of current_window_handle94 new_key = tab_link.split("://")[1].split("/")[0]95 if (new_key in [key.split('_')[0] for key in self.tabs.keys()]): #if tab(s) with this website already exist(s), create new_key: key+"_(i+1)"96 new_key += "_" + str(max([int(key.split('_')[1]) for key in self.tabs.keys() if (key.split("_")[0] == new_key)])+1)97 else: #if tabs with this website don't exist yet98 new_key += "_1"99 self.tabs[new_key] = {}100 self.tabs[new_key]['link'] = tab_link101 self.tabs[new_key]['handle'] = tab_handle102 if switch_to_tab: self.switch_to_tab(new_key)103 #check that remove tab from tabs and add tab to tabs work correctly one after another104 def modify_tabkey_value(self, tab_key, tab_link, switch_to_tab=True): #modifies the value in self.tabs[tab_key] since a new link was followed on this tab105 self.tabs.pop(tab_key)106 self.add_tab_to_tabs(tab_link, switch_to_tab) #want to switch to the tab in order for self.current_tab_key to be updated107 def refresh(self):108 self.chrome.refresh()...

Full Screen

Full Screen

window_handler.py

Source:window_handler.py Github

copy

Full Screen

...5 print(f'Browser located "{str(len(windows))}" tabs, please review.')6 input()7 else:8 return windows9def switch_to_tab(browser, window, type, alt):10 try:11 browser.switch_to.window(browser.window_handles[window])12 except WebDriverException:13 if not alt:14 print(f'Failed to switch to "{type}" window tab, please review.')15 input()16def switch_to_event_tab(browser, alt=False):17 windows = get_window_handles(browser)18 if len(windows) == 2:19 switch_to_tab(browser, 1, "event", alt)20 return windows21def close_event_tab(browser):22 windows = switch_to_event_tab(browser, alt=True)23 if len(windows) == 2:24 browser.close()25 switch_to_tab(browser, 0, "main", alt=False)...

Full Screen

Full Screen

test_work_with_multiple_tabs.py

Source:test_work_with_multiple_tabs.py Github

copy

Full Screen

...3todomvc = TodoMVC()4class TestWithMultipleTabs:5 def test_open_and_close_new_tab(self):6 todomvc.open_in_new_tab('https://github.com/yashaka/selene')7 todomvc.switch_to_tab(1)8 todomvc.check_tab_name("GitHub - yashaka/selene: User-oriented Web UI browser tests in Python")9 browser.close_current_tab()10 todomvc.switch_to_tab(0)11 todomvc.check_tab_name("React • TodoMVC")12 def test_work_in_two_tabs(self):13 todomvc.add('a', 'b', 'c')14 todomvc.open_in_new_tab('#/')15 todomvc.switch_to_tab(1)16 todomvc.assert_text('a', 'b', 'c')17 todomvc.delete('c')18 todomvc.switch_to_tab(0)19 todomvc.assert_text('a', 'b')20 todomvc.edit_enter('b', ' edited')21 todomvc.switch_to_tab(1)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumBase automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful