在Selenium中使用Firefox Profile遇Unicode转义错误求助
解决Selenium中Firefox Profile路径的Unicode转义错误
你的代码报错是因为Python将路径字符串里的\U识别为Unicode转义序列的起始,但后续没有完整的8位十六进制字符,导致解析失败。以下是三种可行的修复方案:
使用原始字符串:在路径字符串前添加
r,让Python忽略转义字符fp = webdriver.FirefoxProfile(r'C:\Users\tommy\AppData\Roaming\Mozilla\Firefox\Profiles\jfrxn7d4.default-release')替换为双反斜杠:用两个反斜杠表示实际的单个反斜杠,避免转义冲突
fp = webdriver.FirefoxProfile('C:\\Users\\tommy\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\jfrxn7d4.default-release')改用正斜杠:Windows系统支持正斜杠作为路径分隔符,彻底规避转义问题
fp = webdriver.FirefoxProfile('C:/Users/tommy/AppData/Roaming/Mozilla/Firefox/Profiles/jfrxn7d4.default-release')
额外提示:Selenium 4+ 推荐写法
新版本Selenium已不推荐使用FirefoxProfile,建议用Options类加载配置文件,兼容性更好:
from selenium import webdriver from selenium.webdriver.firefox.options import Options from time import sleep options = Options() options.profile = r'C:\Users\tommy\AppData\Roaming\Mozilla\Firefox\Profiles\jfrxn7d4.default-release' driver = webdriver.Firefox(options=options) driver.get("https://www.google.com/")
内容的提问来源于stack exchange,提问作者Thomas Tsiftilis
相关产品推荐
相关产品推荐

