Selenium:FirefoxProfile 失败,出现未找到异常

3 投票
1 回答
4887 浏览
提问于 2025-04-16 21:16

我有以下这段代码,虽然我设置了 profile_directory,但是 Firefox 的自动化工具还是试图把设置存储在 /tmp 文件夹里。

profile = FirefoxProfile(profile_directory = '/home/sultan/profiles')
profile.set_preference('network.proxy.http', scheme);
profile.set_preference('network.proxy.http_port', self.proxy.get('port'));

异常代码:

File "/home/sultan/Repository/Django/monitor/app/utils.py", line 79, in start
    request.perform(scan = scan, schedule = schedule)
File "/home/sultan/Repository/Django/monitor/app/request.py", line 230, in perform
    profile1 = FirefoxProfile(profile_directory = '/home/sultan/profiles')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 97, in __init__
    self._read_existing_userjs()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 178, in _read_existing_userjs
    f = open(os.path.join(self.profile_dir, 'user.js'), "r")
IOError: [Errno 2] No such file or directory: '/tmp/webdriver-py-profilecopy/user.js'

我哪里做错了,或者我需要为 selenium 添加一些特定的配置吗?

1 个回答

3

我也遇到过同样的问题。因为Firefox 5没有“user.js”这个文件,所以我们就不需要去读取它。

所以打开selenium/webdriver/firefox/firefox_profile.py,然后在def _read_existing_userjs(self)这个函数后面加上try except,像这样:

def _read_existing_userjs(self):
    try:
        f = open(os.path.join(self.profile_dir, 'user.js'), "r")
    except IOError, e:
        print "We didn't find user.js in your profile, but that is ok"
        return

    tmp_usr = f.readlines()
    f.close()
    for usr in tmp_usr:
        matches = re.search('user_pref\("(.*)",\s(.*)\)', usr)
        self.default_preferences[matches.group(1)] = matches.group(2)

撰写回答