Get the App
SLTechnology News&Howtos  ›  Development  › 

How to switch the python web page window

Shulou Source: shulou.com Published: 2022-06-03 17:38:57 10月02日 Update

This article will explain in detail how to switch Python web page windows, Xiaobian thinks it is quite practical, so share it for everyone to make a reference, I hope you can gain something after reading this article.

When doing web automation, there are times when an element that opens a new window and can't find another window in the current window appears, and window switching is needed.

description

The premise of window switching is to trigger a new window, a new window (usually using a handle) and get the handle of the window.

2. diver.window_handles Gets all handles of the window, has a return value, and needs a variable to receive.

Returns a list in which the most recently opened window handle is the last value in the list.

switching window

diver.switch_to.window

examples

from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium. webdriver.support import expected_conditions as ECimport time#Open a session diver = webdriver.Chrome()#Full screen diver.maximize_window()diver.implicitly_wait(30) try: #Visit Baidu link diver.get("https://www.baidu.com") WebDriverWait(diver, 20).until(EC.visibility_of_element_located((By.ID, "kw"))) #Wait for text box to be visible diver.find_element_by_id("kw").send_keys("Baidu Post Bar") #Input Content WebDriverWait(diver, 20).until(EC.visibility_of_element_located((By.ID, "su"))) #Wait for hundreds to be visible diver.find_element_by_id("su").click() #Click WebDriverWait(diver, 20).until( EC.visibility_of_element_located((By.XPATH, '//a[text()="ba- "$>'))) diver.find_element_by_xpath ('//a[text()="ba- "]').click() #Click time.sleep(3) handles_list = diver.window_handles print(handles_list)#Get handles for all windows diver.switch_to.window(handles_list[-1]) #Switch to last window--Switch to new html page #Waiting for Baidu Post Bar to be visible WebDriverWait(diver, 20).until( EC.visibility_of_element_located(( By.ID,"tab_picture"))) #Wait for picture button to be visible diver.find_element_by_id("tab_picture").click() time.sleep(3) #quit diver.quit()except Exception as e: #quit diver.quit() raise e about "python web page window how to switch" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Tags: Switch handle article web page content more Baidu Tieba post bar good practical element brand new premise variable picture instance form button text article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux macOS Shulou Information Shulou Tech Info MySQL