Почему браузер chrome не запускается при запуске драйвера Selenium chrome в Ubuntu 18.04 - PullRequest
0 голосов
/ 30 января 2020

Я получаю различные ошибки при попытке запустить программу python с использованием библиотеки Selenium и chromedriver. Я следую инструкциям на веб-сайте Selenium, чтобы установить все, что мне нужно, и затем начинаю программировать две первые строки:

from selenium.webdriver import Chrome
driver = Chrome() 

Я получил это сообщение об ошибке:

WebDriverException                        Traceback (most recent call last)
<ipython-input-16-dce6fb94cc37> in <module>
      1 from selenium.webdriver import Chrome
      2 
----> 3 driver = Chrome()

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive)
     79                     remote_server_addr=self.service.service_url,
     80                     keep_alive=keep_alive),
---> 81                 desired_capabilities=desired_capabilities)
     82         except Exception:
     83             self.quit()

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in __init__(self, command_executor, desired_capabilities, browser_profile, proxy, keep_alive, file_detector, options)
    155             warnings.warn("Please use FirefoxOptions to set browser profile",
    156                           DeprecationWarning, stacklevel=2)
--> 157         self.start_session(capabilities, browser_profile)
    158         self._switch_to = SwitchTo(self)
    159         self._mobile = Mobile(self)

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in start_session(self, capabilities, browser_profile)
    250         parameters = {"capabilities": w3c_caps,
    251                       "desiredCapabilities": capabilities}
--> 252         response = self.execute(Command.NEW_SESSION, parameters)
    253         if 'sessionId' not in response:
    254             response = response['value']

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243 
    244     def _value_or_default(self, obj, key, default):

WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/chromium-browser is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

, поэтому я прочитал много сообщения и советы от людей, которые рекомендуют добавлять параметры атрибутов раньше. Поэтому я изменяю свой код на этот:

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-extensions')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://google.com')

Но у меня все еще нет запуска браузера windows, и я не могу понять, что происходит ... и мой журнал говорит об этом:

/home/lclis/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:8: DeprecationWarning: use options instead of chrome_options

Я ищу любой совет или предложение, я немного растерялся, большое спасибо за вашу помощь и время, чтобы прочитать мой пост!

PS: я на windows10, но использую приложение Ubuntu для кодирования и использования Jupyter.

Ответы [ 2 ]

0 голосов
/ 30 января 2020

Это первое сообщение об ошибке ...

WebDriverException                        Traceback (most recent call last)
<ipython-input-16-dce6fb94cc37> in <module>
      1 from selenium.webdriver import Chrome
      2 
----> 3 driver = Chrome()

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive)
     79                     remote_server_addr=self.service.service_url,
     80                     keep_alive=keep_alive),
---> 81                 desired_capabilities=desired_capabilities)
     82         except Exception:
     83             self.quit()

... означает, что ChromeDriver не смог запустить / создать новый Контекст просмотра т.е. Chrome Браузер сеанс.

В идеале, ваш кодовый блок должен работать из коробки, но, поскольку вы используете anaconda3 с ipython, вам нужно передать ключ executable_path вместе с значением , установленным на абсолютный путь ChromeDriver следующим образом:

from selenium.webdriver import Chrome
driver = Chrome(executable_path='/path/to/chromedriver') 

Тем не менее, во втором испытании кода вы были довольно близки. Это второе сообщение об ошибке ...

/home/lclis/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:8: DeprecationWarning: use options instead of chrome_options

... означает, что ChromeDriver снова не смог инициировать / порождать новый Контекст просмотра т.е. Chrome Браузер сессия.

Вместо chrome_options вы должны были использовать options следующим образом:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-extensions')
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://google.com')
0 голосов
/ 30 января 2020

Если я не ошибаюсь, поскольку вы добавили опцию headless, браузер не откроет ни одного окна.

Попробуйте удалить эту строку: chrome_options.add_argument('--headless')

...