You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium在Safari中调用find_element方法程序无响应求助

解决Safari下Selenium find_element挂起的问题

问题重现

在macOS 14.1.2、Safari 17.1.2、Python 3.12、Selenium 4.16环境中,设置page_load_strategy='none'后,调用find_element时程序无响应挂起,但Firefox下相同代码正常运行。

可能原因

Safari的WebDriver对none加载策略的实现和Firefox存在差异:none模式下浏览器不会等待页面任何加载完成信号就执行后续代码,但Safari在这种状态下执行元素查找时,可能因为DOM未就绪导致内部阻塞,无法返回结果。

解决方案

方案1:更换页面加载策略

将page_load_strategy改为eager(等待DOM加载完成)或默认的normal(等待所有资源加载完成),这两种策略能确保DOM就绪后再执行元素查找,避免挂起:

from selenium import webdriver
from selenium.webdriver.common.by import By

browser_name = 'safari'
find_browser = True

if browser_name == 'firefox':
    firefox_option = webdriver.FirefoxOptions()
    firefox_option.page_load_strategy = 'none'
    browser = webdriver.Firefox(options=firefox_option)
elif browser_name == 'safari':
    safari_option = webdriver.SafariOptions()
    safari_option.page_load_strategy = 'eager'  # 替换为eager或移除该行用默认normal
    browser = webdriver.Safari(options=safari_option)
else:
    print('Wrong browser name!')
    find_browser = False

if find_browser:
    browser.get('http://inventwithpython.com')
    try:
        element = browser.find_element(By.CLASS_NAME, 'row')
        print(f'Found <{element.tag_name}> element with that class name!')
        browser.close()
    except Exception as e:
        print(f'Was not able to find an element with that name: {str(e)}')

方案2:保留none策略并添加显式等待

如果必须使用none策略,需要通过WebDriverWait显式等待元素出现,避免直接调用find_element导致阻塞:

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

browser_name = 'safari'
find_browser = True

if browser_name == 'firefox':
    firefox_option = webdriver.FirefoxOptions()
    firefox_option.page_load_strategy = 'none'
    browser = webdriver.Firefox(options=firefox_option)
elif browser_name == 'safari':
    safari_option = webdriver.SafariOptions()
    safari_option.page_load_strategy = 'none'
    browser = webdriver.Safari(options=safari_option)
else:
    print('Wrong browser name!')
    find_browser = False

if find_browser:
    browser.get('http://inventwithpython.com')
    try:
        # 等待10秒,直到元素出现
        element = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'row'))
        )
        print(f'Found <{element.tag_name}> element with that class name!')
        browser.close()
    except Exception as e:
        print(f'Was not able to find an element with that name: {str(e)}')
        browser.close()

方案3:检查Safari远程自动化设置

确保Safari已开启远程自动化:

  • 打开Safari,点击菜单栏Safari->设置->高级,勾选显示开发菜单
  • 点击菜单栏开发->允许远程自动化

内容的提问来源于stack exchange,提问作者unCLAD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:10:13