当前位置: 首页 > 图灵资讯 > 行业资讯> python网页窗口如何切换

python网页窗口如何切换

发布时间:2024-06-28 21:28:49

当web自动化时,有时会打开新窗口,在当前窗口中找不到另一个窗口元素,需要使用窗口切换。

说明

1、窗口切换的前提是触发新窗口、新窗口(通常使用句柄)和获取窗口的句柄。

2、per.window_handles获取窗口中的所有句柄,具有返回值,需要变量接收。

以列表的形式返回,最新打开的窗口句柄是列表中的最后一个值。

切换窗口

per.switch_to.window("切换窗口的句柄")

实例

fromseleniumimportwebdriver
fromselenium.webdriver.common.byimportBy
fromselenium.webdriver.support.waitimportWebDriverWait
fromselenium.webdriver.supportimportexpected_conditionsasEC
importtime
#打开会话
per=webdriver.Chrome()
#全屏
per.maximize_window()
per.implicitly_wait(30)

try:
#访问百度链接
per.get("https://www.baidu.com")
WebDriverWait(per,20).until(EC.visibility_of_element_located((By.ID,"kw")))
#等待文本框可见
per.find_element_by_id("kw").send_keys("百度贴吧")#输入内容
WebDriverWait(per,20).until(EC.visibility_of_element_located((By.ID,"su")))
#等百度一下就能看到
per.find_element_by_id("su").click()#点击
WebDriverWait(per,20).until(
EC.visibility_of_element_located((By.XPATH,'//a[text()="吧-"]')))
per.find_element_by_xpath('//a[text()="吧-"]').click()#点击
time.sleep(3)
handles_list=per.window_handles
print(handles_list)#获取所有窗口的handle
per.switch_to.window(handles_list[-1])#切换到最后一个窗口-切换到新的html页面
#等待百度贴吧可见
WebDriverWait(per,20).until(
EC.visibility_of_element_located((
By.ID,"tab_picture")))#等待图片按钮可见
per.find_element_by_id("tab_picture").click()
time.sleep(3)
#退出
per.quit()
exceptExceptionase:
#退出
per.quit()
raisee

以上是python网页窗口的切换方法,希望对大家有所帮助。更多Python学习指导:python基础教程

本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。

相关文章

如何让vim支持python3

如何让vim支持python3

2025-09-12
python2.7和3.6区别有哪些

python2.7和3.6区别有哪些

2025-09-12
python3有serial库吗

python3有serial库吗

2025-09-12
python中w、r表示什么意思

python中w、r表示什么意思

2025-09-12
python中如何把list变成字符串

python中如何把list变成字符串

2025-09-12
python命名空间是什么

python命名空间是什么

2025-09-12