加快ui显示速度 by iframe

本文探讨了一种策略,在页面body标记的顶部的Iframe中加载JavaScript,以实现并行加载,避免浏览器卡顿。通过使用Closure等工具解决代码复杂度问题,实现了速度提升。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 iFrame:

为了能并行的加载JavaScript,避免浏览器卡住(http://goo.gl/lzGq8),我在页面的body标记的顶部的一个Iframe里加载JavaScript。在iframe里加载JavaScript增加了代码的复杂度(通过Closure,我们很好的解决了这个问题),但是为了速度的提升,值得这样做。

from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException, WebDriverException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def init_driver(): chrome_options = Options() # 基础配置 chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--headless=new") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--single-process") # 强化反检测配置 chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False) # 初始化Driver(确保路径正确) service = Service(executable_path="/usr/bin/sensible-browser") driver: WebDriver = webdriver.Chrome(service=service) # 覆盖WebDriver属性 driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', { 'source': ''' Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); ''' }) return driver # 安全初始化Driver变量 driver = None try: driver = init_driver() driver.get('http://portal.sx.cmcc/home') # 显式等待元素可见(非仅存在) wait = WebDriverWait(driver, 15) main_content = wait.until( EC.visibility_of_element_located((By.ID, "main-content")) ) print("成功加载目标元素!") except TimeoutException as e: print(f"页面元素加载超时: {str(e)}") except WebDriverException as e: print(f"浏览器驱动异常: {str(e)}") if "net::ERR_NAME_NOT_RESOLVED" in str(e): print("提示:请检查网址是否正确或网络连接是否正常") except Exception as e: print(f"未知错误: {str(e)}") finally: if driver: driver.quit() else: print("警告:Driver未成功初始化,无需退出")
最新发布
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

折腾数据折腾代码

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

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

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

打赏作者

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

抵扣说明:

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

余额充值