Как загрузить профиль Firefox с помощью Python Selenium?
Я пытаюсь заставить Python Selenium работать на моей Windows-машине. Я обновил до последних версий Firefox, Selenium, Geckodriver, но все равно получаю следующую ошибку:
Python Script
from selenium import webdriver
driver = webdriver.Firefox()
ошибка
Traceback (most recent call last):
File "run.py", line 17605, in <module>
File "<string>", line 21, in <module>
File "site-packages\selenium\webdriver\firefox\webdriver.py", line 77, in __init__
File "site-packages\selenium\webdriver\firefox\extension_connection.py", line 49, in __init__
File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 68, in launch_browser
File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 103, in _wait_until_connectable
WebDriverException: Message: Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details.
Я также попытался создать профиль Firefox с помощью приведенного ниже кода:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/vnd.ms-excel'))
profile.set_preference('general.warnOnAboutConfig', False)
gecko_path = "path_to_geckodriver\\geckodriver.exe"
path = "path_to_firefoxs\\Mozilla Firefox\\firefox.exe"
binary = FirefoxBinary(path)
driver = webdriver.Firefox(firefox_profile=profile,executable_path=gecko_path)
- Python 2.7
- Firefox 60
- Geckodriver-v0.20.1-win64.zip
- Селен 3.12.0
2 ответа
Я боролся, пока не нашел эту проблему, которая теперь решена, но была полезна, потому что она показывает некоторые команды.
from selenium import webdriver
fp = webdriver.FirefoxProfile('/home/gabriel/.mozilla/firefox/whatever.selenium')
driver = webdriver.Firefox(fp)
первая версия, не работает, потому что я не мог соединиться с селеном потом:
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
options = Options()
options.add_argument("-profile")
options.add_argument("/home/gabriel/.mozilla/firefox/whatever.selenium")
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
driver = webdriver.Firefox(capabilities=firefox_capabilities, firefox_options=options)
Я уверен, что это загружает профиль "what.selenium", потому что если я перейду к about:profile, я могу прочитать:
Профиль: селен Это профиль используется и не может быть удален.
Хотя "what.selenium" не является профилем по умолчанию в моей системе.
Примечание: по крайней мере один параметр профиля переопределяется селеном (или geckodriver?): "Предпочтения"> "Конфиденциальность и безопасность"> "Блокировать всплывающие окна" всегда сбрасывается. Так что используйте about: профили, чтобы утверждать, на каком профиле вы работаете.
заметки:
firefox_capabilities
может не понадобиться в приведенном выше коде.- протестировано под Firefox 60.4.0esr (64-разрядная версия), geckodriver 0.23.0 ( 2018-10-04), селен 3.141.0 с Python 3.5.3
В окнах я использую:
fp = webdriver.FirefoxProfile('C:/Users/x/AppData/Roaming/Mozilla/Firefox/Profiles/some-long-string')
driver = webdriver.Firefox(firefox_profile=fp)
...
1 - Чтобы найти текущий Profile Folder
, тип about:support
в поле url и нажмите Enter.
2 - Чтобы увидеть все профили пользователей, введитеabout:profiles
в поле url и нажмите Enter.
Вы не обновляли настройки для profile: profile.update_preferences (). Вы должны обновить профиль после установки предпочтений. Следуйте приведенному ниже коду:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/vnd.ms-excel'))
profile.set_preference('general.warnOnAboutConfig', False)
profile.update_preferences()
gecko_path = "path_to_geckodriver\\geckodriver.exe"
path = "path_to_firefoxs\\Mozilla Firefox\\firefox.exe"
binary = FirefoxBinary(path)
driver = webdriver.Firefox(firefox_profile=profile,executable_path=gecko_path)
Переключитесь на хромированный драйвер. Firefox, геккон и селен сейчас не очень хорошо работают вместе. Вот что наконец-то сработало для меня.
import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
class TestTemplate(unittest.TestCase):
"""Include test cases on a given url"""
def setUp(self):
"""Start web driver"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.driver.implicitly_wait(10)
def tearDown(self):
"""Stop web driver"""
self.driver.quit()
def test_case_1(self):
"""Go to python.org and print title"""
try:
self.driver.get('https://www.python.org/')
title = self.driver.title
print title
except NoSuchElementException as ex:
self.fail(ex.msg)
def test_case_2(self):
"""Go to redbull.com and print title"""
try:
self.driver.get('https://www.redbull.com')
title = self.driver.title
print title
except NoSuchElementException as ex:
self.fail(ex.msg)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestTemplate)
unittest.TextTestRunner(verbosity=2).run(suite)
Я использую Jenkinsfile, который загружает буфер кадра для вызова selenium и скрипта Python.
Вы можете легко запустить это на своей локальной машине. Возможно, вы захотите получить бродячую коробку с Linux.
Вот что запускает скрипт Python.
sh "(Xvfb: 99-screen 0 1366x768x16 &) && (python./$ndomPYTHON_SCRIPT_FILE})"
Это вызывается из файла Docker, выполняющего этот образ Docker.
Загрузка настроенного профиля Firefox в Java:
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
options.setProfile(selenium_profile);
options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pburgr\\Desktop\\geckodriver-v0.20.0-win64\\geckodriver.exe");
driver = new FirefoxDriver(options);
driver.manage().window().maximize();