selenium有多个frame页时的操作方法(5)

之前文章我们提到,在webdriver.WebDriver类有一个switch_to方法,通过switch_to.frame()可以切换到不同的frame页然后才再定位某个元素做一些输入/点击等操作。

比如下面这个测试网站有2个frame页:http://www.sahitest.com/demo/framesTest.htm,每个frame页的元素是一样的。

检查下Link Test的元素信息,发现两个frame,在每个frame下面都有这个元素的相同信息。

每个frame中的相同的元素信息都一样:

switch_to.frame方法

当我们定义好driver对象,打开网页并使用driver.switch_to.frame()方法切换frame时,该方法其实调用了selinium中的SwitchTo类中的frame方法:

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Safari()
# 打开一个网页
driver.get("http://www.sahitest.com/demo/framesTest.htm")

方法中的参数frame_reference可以是fame的name,或者代表frame的数字(从0开始),或者是该frame元素位置,如函数中的的介绍。

  • driver.switch_to.frame('frame_name')
  • driver.switch_to.frame(1)
  • driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0])
复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Safari()
# 打开一个网页
driver.get("http://www.sahitest.com/demo/framesTest.htm")
driver.maximize_window()
sleep(2)

#先切换到第1个frame
driver.switch_to.frame(0)
sleep(1)
#点击TestLink链接
driver.find_element(By.XPATH,'/html/body/table/tbody/tr/td[1]/a[1]').click()
sleep(2)

#完成后 先返回上一级frame或者默认frame 然后才能切换到第2个frame
#以下两个方法都可使用
driver.switch_to.default_content()
#driver.switch_to.parent_frame()

#切换第2个frame
driver.switch_to.frame(1)
sleep(1)
driver.find_element(By.XPATH,'/html/body/table/tbody/tr/td[1]/a[1]').click()
sleep(4)

共勉: 东汉·班固《汉书·枚乘传》:"泰山之管穿石,单极之绠断干。水非石之钻,索非木之锯,渐靡使之然也。"

-----指水滴不断地滴,可以滴穿石头;

-----比喻坚持不懈,集细微的力量也能成就难能的功劳。

----感谢读者的阅读和学习,谢谢大家。

相关推荐
月亮!3 分钟前
当技术中立性遇上算法偏见:软件测试者的伦理启示
网络·人工智能·python·测试工具·算法·安全·开源
wonder135795 分钟前
RectTransform位置计算方法和UI自适应
ui·unity·ugui
曲幽5 分钟前
Flask核心技能:从零上手视图函数
python·json·app·web·get·post·request·response
晞微11 分钟前
PyTorch 实现 BP 神经网络:从函数拟合到分类任务
pytorch·python·神经网络·分类
薛不痒13 分钟前
机器学习之Python中的numpy库,pandas库
开发语言·python
计算衎13 分钟前
FastAPI+ PostgreSQL+ VUE 实现一个数据平台展示案例
vue.js·python·postgresql·fastapi
Keep__Fighting15 分钟前
【机器学习:K-Means】
人工智能·python·算法·机器学习·kmeans·聚类·sklearn
yeshihouhou16 分钟前
redis(zset使用)使用场景案例
前端·redis·python
知识进脑的肖老千啊16 分钟前
深度学习下载包时可能会遇到的问题及解决方案
人工智能·python·深度学习
徐1116 分钟前
deppseek优化怎么做? GEO技术具体解决方案
人工智能·python