• 技术文章 >Python技术 >Python基础教程

    python网页窗口如何切换

    小妮浅浅小妮浅浅2021-09-13 09:37:02原创4466

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

    说明

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

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

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

    切换窗口

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

    实例

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import time
    #打开一个会话
    diver = webdriver.Chrome()
    #全屏
    diver.maximize_window()
    diver.implicitly_wait(30)
     
    try:
        # 访问百度链接
        diver.get("https://www.baidu.com")
        WebDriverWait(diver, 20).until(EC.visibility_of_element_located((By.ID, "kw")))
        # 等待文本框可见
        diver.find_element_by_id("kw").send_keys("百度贴吧")  # 输入内容
        WebDriverWait(diver, 20).until(EC.visibility_of_element_located((By.ID, "su")))
        # 等待百度一下可见
        diver.find_element_by_id("su").click()  # 点击
        WebDriverWait(diver, 20).until(
            EC.visibility_of_element_located((By.XPATH, '//a[text()="吧 - "]')))
        diver.find_element_by_xpath('//a[text()="吧 - "]').click()  # 点击
        time.sleep(3)
        handles_list = diver.window_handles
        print(handles_list)# 获取所有窗口的handle
        diver.switch_to.window(handles_list[-1])  # 切换到最后一个窗口——切换到全新的html页面
        # 等待百度贴吧可见
        WebDriverWait(diver, 20).until(
            EC.visibility_of_element_located((
                By.ID,"tab_picture")))  # 等待图片按钮可见
        diver.find_element_by_id("tab_picture").click()
        time.sleep(3)
        # 退出
        diver.quit()
    except Exception as e:
        # 退出
        diver.quit()
        raise e

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

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

    专题推荐:python网页窗口
    品易云
    上一篇:python ChainMap增加子上下文的方法 下一篇:python ChainMap跳过子上下文的功能

    相关文章推荐

    • python OpenCV的图像处理• python中Qt是什么• python浏览器操作有哪些• python等待方式的介绍• 常用6种顶级Python文本编辑器• python中ChainMap是什么• python中ChainMap如何实例化• python中ChainMap如何创建对象• python ChainMap如何实现字典操作• python update合并字典的方法• python ChainMap如何管理映射列表• python ChainMap增加子上下文的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网