【爬虫基础】第25讲 定位iframe中的对象

 在web 应用中经常会出现frame 嵌套的应用。在使用 Selenium 进行 Web 自动化测试时,定位 iframe 可以通过以下几种方式实现:

第一种——通过索引定位:

driver.switch_to.frame(0)  # 切换到第一个 iframe
# 在 iframe 中进行操作
driver.switch_to.default_content()  # 切换回默认的主页面

第二种——通过名称或 ID 定位:

driver.switch_to.frame("iframe_name")  # 通过名称定位
# 在 iframe 中进行操作
driver.switch_to.default_content()  # 切换回默认的主页面

driver.switch_to.frame("iframe_id")  # 通过 ID 定位
# 在 iframe 中进行操作
driver.switch_to.default_content()  # 切换回默认的主页面

第三种——通过元素定位:

from selenium.webdriver.common.by import By

# 先定位到父元素
parent_element = driver.find_element(By.XPATH, "父元素定位表达式")
# 再通过父元素找到子 iframe 元素
iframe_element = parent_element.find_element(By.XPATH, "子元素定位表达式")

driver.switch_to.frame(iframe_element)  # 切换到指定的 iframe
# 在 iframe 中进行操作
driver.switch_to.default_content()  # 切换回默认的主页面


实战:

下面的代码中frame.html 里有个id 为f1 的frame,而f1 中又嵌入了id 为f2 的frame,该frame 加载了搜狗的首页。

frame.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-Frame-Options" content="allow">
    <title>Document</title>
</head>
<body>
    <div >
        <h3>frame</h3>
        <iframe id="f1" src="inner.html" width="900" height="600"></iframe>
    </div>
</body>
</html>

inner.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-Frame-Options" content="allow">
    <title>Document</title>
</head>
<body>
    <h3>inner</h3>
    <iframe id="f2" src="https://www.sogou.com/" width="800" height="400">
    </iframe>
    
</body>
</html>

mian.py

from selenium import webdriver
import os
from time import sleep

def test01():
    chrome = webdriver.Chrome()
    file_path = 'file:///'+os.path.abspath('./1/html/iframe.html')
    chrome.get(file_path)

    chrome.switch_to.frame('f1')
    chrome.switch_to.frame('f2')

    chrome.find_element_by_id('query').send_keys('python')
    chrome.find_element_by_id('stb').click()
    sleep(5)

if __name__=="__main__":
    test01()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值