iframe里元素获取

from PIL.SpiderImagePlugin import iforms
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
# <iframe id="LR_miniframe" name="LR_miniframe" width="100%" height="400px" frameborder="0" scrolling="No" allowtransparency="true" src="about:blank"></iframe>
#     <div id="centerMsg" >
#     <iframe id="FreeTextBox1_editor" name="FreeTextBox1_editor" style="BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-BOTTOM-STYLE: none; " frameborder="0" hspace="0" height="61" width="100%" src="about:blank">
#         <body onkeydown="return parent.f11(event);" onkeyup="return parent.f12(event)" onmousedown="return parent.editclick(event);" onfocus="return parent.editfocus()" onblur="return parent.editblur()" contenteditable="true" style="font-family: 微软雅黑; font-weight: normal; font-style: normal; font-size: 10pt; text-decoration: none; color: rgb(153, 153, 153);">请在此输入文本或者粘贴QQ截图</body>
#     </iframe>
#     <div id="SendBar">
#     </div>
# </iframe>
# 初始化webdriver,这里以Chrome为例
driver = webdriver.Chrome()

# 设置隐式等待时间,单位为秒
driver.implicitly_wait(10)

# 打开目标网页
driver.get('https://example.com')
#通过js加载元素的 需要先找到iframe元素 再切换到iframe 再查找元素 最后切换回主文档

try:
    # 等待页面加载完成后,再等待几秒钟让聊天弹框出现
    time.sleep(5)  # 等待5秒,可以根据实际情况调整

    # 打印当前页面的标题和URL,确保页面加载正确
    print(f"Page title: {driver.title}")
    print(f"Page URL: {driver.current_url}")

    # 查找iframe元素
    iframe = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "LR_miniframe"))
    )

    # 切换到iframe
    driver.switch_to.frame(iframe)

    # 尝试通过ID定位元素
    try:
        element = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.ID, "centerMsg"))
        )
        try:
            iframe1 = WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.ID, "FreeTextBox1_editor"))
            )
            print("Element found using FreeTextBox1_editor.")
            driver.switch_to.frame(iframe1)
            # 查找具有特定属性的 <body> 元素
            body_element = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH,
                                                "//body[@contenteditable='true' and @style='font-family: 微软雅黑; font-weight: normal; font-style: normal; font-size: 10pt; text-decoration: none;']"))
            )

            # 操作 <body> 元素,例如输入文本
            body_element.clear()
            body_element.send_keys("例如输入文本")
            time.sleep(3)
            #切换到主文档
            driver.switch_to.default_content()
            iframe = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.ID, "LR_miniframe"))
            )
            #切换到外层的iframe
            driver.switch_to.frame(iframe)
            # 点击发送按钮
            send_button = WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.ID, "SendBar"))
            )
            send_button.click()
            print("Text sent successfully.")
        except TimeoutException:
            print("Element not clickable using ID. Trying XPath...")


        print("Element found using ID.")
    except TimeoutException:
        print("Element not found using ID. Trying XPath...")

        # 尝试通过XPath定位元素
        element = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//div[@id='centerMsg']"))
        )
        print("Element found using XPath.")

    print("Element is ready!")
except TimeoutException as te:
    print(f"TimeoutException: Element not found within the given time. {te}")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # 切换回主文档
    driver.switch_to.default_content()

    # 保存当前页面的截图,以便调试
    driver.save_screenshot('screenshot.png')

    # 打印页面的HTML源代码,以便调试
    with open('page_source.html', 'w', encoding='utf-8') as file:
        file.write(driver.page_source)

    # 关闭浏览器窗口
    driver.quit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值