Article From:https://www.cnblogs.com/ygzy/p/9558913.html

1、Recognizing multiple windows

  • Some pages will reopen a browser label after the link is opened. If you want to operate on a new window, you have to switch the window first.
  • The unique identifier of the window is the handle, and it can be manipulate as long as it switches to the corresponding wide handle.
  • Actual scenes, such as Ganji network, will have a window when working.

2、Handle operation

  • Elements have attributes, windows have attributes, but you can’t see them. Browser attributes are identified by handles
  • Gets the handle of the current window: driver.current_window_handle
  • Get all window handles: window_hadnle
  • Toggle window: driver.switch_to.window ()
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://sh.ganji.com/")
driver.implicitly_wait(5)
handle1 = driver.current_window_handle
print("Current window handle"+handle1)
print(driver.title)

driver.find_element_by_xpath('//a[@href="zhaopin/"]/span[1]').click()

#All the handles obtained are a list and are switched through the list element subscript.
handles = driver.window_handles
print("All window handles"+handles)

#switch windows
driver.switch_to.window(handles[1])
current_handle = driver.current_window_handle
print("Current window handle"+current_handle)
print(driver.title)
#Close the current window
driver.close()
time.sleep(2)
#End browser process
driver.quit()

 

Leave a Reply

Your email address will not be published. Required fields are marked *