selenium定位层级内元素

selenium_定位层级内元素

image-20220522123922563

1 窗口的定位

对于一个现代的web应用,经常会出现框架(frame) 或窗口(window)的应用,这也就给我们的定位带来了一个难题。

有时候我们定位一个元素,定位器没有问题,但一直定位不了,这时候就要检查这个元素是否在一个frame中,seelnium webdriver 提供了一个switch_to_frame方法,可以很轻松的来解决这个问题

多层框架或窗口的定位:

  • driver.switch_to.frame()

1.1 frame.html

<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>frame</title>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
  <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css"
    rel="stylesheet" />
</head>


<body>
  <div class="row-fluid">
    <div class="span10 well">
      <h3>frame</h3><iframe id="f1" src="inner.html" width="800" , height="600"></iframe>
    </div>
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.8/dist/js/bootstrap.min.js"></script></html>
</html>

1.2 inner.html

<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>inner</title>
</head>
<body>
  <div class="row-fluid">
    <div class="span6 well">
      <h3>inner</h3><iframe id="f2" src="https://cn.bing.com/" width="700" height="500"></iframe>
    </div>
  </div>
</body>
</html>

2 switch_to_frame()

from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By


import os
from time import sleep


def select_frame():
  # 创建驱动
  s = Service(executable_path='./chromedriver.exe')
  # 创建浏览器
  driver = webdriver.Chrome(service=s)
  file_path = 'file:///' + os.path.abspath('./html/outer.html')
  # 打开网页
  driver.get(file_path)
  # 切换frame
  driver.switch_to.frame('f1')
  driver.switch_to.frame('f2')
  # 定位元素,输入要搜索的内容
  driver.find_element(By.ID,'sb_form_q').send_keys('百战')
  # 定位按钮,点击搜索
  driver.find_element(By.ID,'search_icon').click()
  sleep(3)


  driver.quit()


if __name__ =='__main__':
  select_frame()

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留不住的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值