0


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/')

元素定位 操作

个人使用的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()

打开新页面

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

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

查询元素点击 并关闭


openChart.find_element(By.PARTIAL_LINK_TEXT, "立即观看").click()
time.sleep(10)
openChart.close()

要点:

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会切换回到最初打开的那个窗口或标签页


本文转载自: https://blog.csdn.net/sinat_41890480/article/details/136330722
版权归原作者 Time is precious 所有, 如有侵权,请联系我们删除。

“selenium初始学习--打开新标签操作”的评论:

还没有评论