• selenium初始学习--打开新标签操作


    selenium 打开新标签操作

    简单说一下使用

    环境 :python 3.9 selenium 4,18

    初始化操作 目的

    打开bilibilie网站并搜索视频(电影) 并点击观看

    操作

    打开应用并搜索网址

    from selenium import webdriver
    import time
    
    from selenium.webdriver.common.by import By
    
    openChart = webdriver.Chrome()
    openChart.get('https://www.bilibili.com/')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    元素定位 操作

    个人使用的xpath

    openChart.find_element(By.XPATH, '//*[@id="nav-searchform"]/div[1]/input').send_keys('我爱你')
    openChart.find_element(By.XPATH, '//*[@id="nav-searchform"]/div[2]').click()
    
    • 1
    • 2

    打开新页面

    有的也免回重新打开一个新页面 然后就获取不到元素定位了 容易发生找不到的现象
    所以 有下面的操作

    openChart.switch_to.window(openChart.window_handles[-1])  # 跳转到不同页面下的新页面.
    time.sleep(1)  # 延长时间确保能捕捉到.
    
    • 1
    • 2

    查询元素点击 并关闭

    
    openChart.find_element(By.PARTIAL_LINK_TEXT, "立即观看").click()
    time.sleep(10)
    openChart.close()
    
    • 1
    • 2
    • 3
    • 4

    要点:

    openChart.window_handles[-1] 中的 [-1] 就是 Python 中列表的索引,表示获取这个列表的最后一个元素。也就是说,openChart.window_handles[-1] 返回的就是最新打开的窗口或者标签页的句柄。然后 openChart.switch_to.window() 函数就可以用这个句柄来切换到这个新打开的窗口或者标签页。
    所以,openChart.switch_to.window(openChart.window_handles[-1]) 就是将控制权切换到最新打开的窗口或标签页

    在Selenium中, window_handles 是一个列表,它包含当前浏览器进程中所有打开的窗口和标签页的句柄(相当于ID或者指针)。这些句柄按照它们被打开的顺序存储在列表中。所以 window_handles[0] 就代表第一个打开的窗口或标签页的句柄。
    当你使用 openChart.switch_to.window(openChart.window_handles[0]) 的时候,Selenium会切换回到最初打开的那个窗口或标签页

  • 相关阅读:
    使用非递归的方式实现归并排序
    MH/T 6040航空材料烟密度试验
    GraphQL的优势和开发模式
    数字图像处理大作业
    k8s 对外发布(ingress)
    Redis无感升级(从低版本3.0-升级至6.0+)
    java8概要
    SpringMVC项目整合SSM统一结果封装
    如何在python中实现capl语言里的回调函数
    如何上传项目到github?
  • 原文地址:https://blog.csdn.net/sinat_41890480/article/details/136330722