Switching tab in the browser.
The main idea:
1. Open the Baidu Home
2. Obtain academic links Baidu home page above
3. Open a new tab in the academic Baidu
4. Get Baidu home page window handle
5. Obtain Baidu academic window handle
6. By switching the page window handle
Exercise scenarios:
1. Open the Baidu Home
2. Obtain academic links Baidu home page above
3. JavaScript statements, open Baidu academic in a new tab by this statement
4. Execute JavaScript statements
5. Obtain window handle Baidu home page
6. Get all handles browser tabs open
7. determine whether the loop handle academic label, if the handle is academic label will be preserved
8. Switch page through window handle, by switch_to.window (tag handler) method
Specific code:
Coding = UTF-8 # Import Time from the Selenium Import webdriver from selenium.webdriver.common.keys Import Keys Driver = webdriver.Chrome () driver.maximize_window () driver.implicitly_wait (6) driver.get ( "HTTP: // the WWW .baidu.com / ") the time.sleep (. 1) the href = driver.find_element_by_link_text (" academic ") .get_attribute ( 'href') # Get academic Baidu home link js = 'window.open (" {} "); '.format (href) #javaScript statement, opened with this statement in a new tab Baidu academic driver.execute_script (js) # execute JavaScript statements baidu_handle = driver.current_window_handle # # get window handle Baidu home page handles = driver.window_handles # Gets the browser open handles all your tabs for handle in the handles: IF = baidu_handle handle:! xueshu_handle handle = Print (baidu_handle, xueshu_handle) Print ( 'window handle now:', driver.current_window_handle) driver.switch_to.window (xueshu_handle) # switch tabs, the original home page Baidu, Baidu Now switch to the academic print ( "now window handle : ", driver.current_window_handle) the time.sleep (2) driver.close () # close the difference between the current tab, close and quit is a closed current page, a browser is closed driver.switch_to.window (baidu_handle) # switch to home Baidu the time.sleep (2) driver.close ()
Reference article: https://blog.csdn.net/u011541946/article/details/69573632