Selenium调用Firefox的Options对象无update_preferences属性怎么解决?
问题原因
Selenium 4.x 版本重构了Firefox配置相关API,update_preferences()是旧版本FirefoxProfile类的专属方法,新版Options类没有提供该接口,因此调用时会抛出AttributeError异常。
解决方案
- 直接删除代码中的
options.update_preferences()行即可:调用options.set_preference()时,配置会直接写入Options对象的内部存储,不需要额外调用更新方法,实例化Firefox驱动时传入options参数会自动加载所有已设置的偏好。 - 如果需要批量修改或读取已设置的配置,可以直接操作
options.preferences字典,所有通过set_preference设置的参数都会保存在该字典中,支持直接增删改查。
修改后可正常运行的代码
from selenium.webdriver import Firefox from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options profile_path = '/home/xxxx/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US/Browser/TorBrowser/Data/Browser/profile.default' options=Options() options.set_preference('profile', profile_path) options.set_preference('network.proxy.type', 1) options.set_preference('network.proxy.socks', '127.0.0.1') options.set_preference('network.proxy.socks_port', 9050) options.set_preference("network.proxy.socks_remote_dns", False) service = Service('/usr/bin/geckodriver') driver = Firefox(service=service, options=options) driver.get("https://www.google.com") driver.quit()
内容的提问来源于stack exchange,提问作者Erling Olsen
相关产品推荐
相关产品推荐

