环境
IDE: Pycharm 2020.2
系统版本: Ubuntu16.04
起因
在使用selenium时,配置浏览器驱动,运行代码出现异常。
代码
from selenium import webdriver
url = "https://www.baidu.com"
driver = webdriver.Chrome()
driver.get(url)
print(driver.page_source)
driver.close()
异常信息
- Chrome
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
- Firefox
selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process
报错原因
chrome和firefox都不支持以root方式启动。
解决方案
- 使用非root用户打开pycharm
- 仅适用于Chrome
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
url = "https://www.baidu.com"
# 添加参数
options = Options()
# 关闭沙盒启动
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(chrome_options = options)
driver.get(url)
print(driver.page_source)
driver.close()