Python 问题解决 | MacOS安装selenium、chromedriver环境配置

环境和笔记:

macOS 10.12.6
Python 3.7.0
PyCharm 2019.1
GitHub:https://github.com/Biosciman

selenium的安装

  1. 在终端terminal中键入 pip install selenium

  2. 在pycharm的preference中安装package,点击 Install Package即可


    pycharm的preference中安装package

chromedriver的下载

找到对应自己Chrome版本的chromedriver

  1. 在终端terminal中键入 brew cask install Chromedriver(需提前安装Homebrew,并且下载Chromedriver国内会响应超时)

  2. https://sites.google.com/a/chromium.org/chromedriver/(国内打不开)

  3. http://npm.taobao.org/mirrors/chromedriver

下载完成后会得到如下文件:


chromedriver文件

chromedriver的配置

官方推荐配置:

#Google推荐配置
import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
driver.get('http://www.google.com/');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()

但是,官方推荐配置会遇到问题:

1. Message: 'chromedriver' executable needs to be in PATH.

'chromedriver' executable needs to be in PATH

解决方法:
a. 将 chromedriver 文件复制到 /usr/local/bin 目录下(推荐)
b. 设置 chromedriver 的绝对地址

import time
from selenium import webdriver
#在webdriver,Chrome()中键入 *chromedriver*  的绝对地址
driver = webdriver.Chrome('absolute directory') 

2. 'chromedriver' executable may have wrong permissions

权限问题。在终端terminal中键入如下代码,给chromedriver 权限。

 sudo chmod +x /usr/local/bin/chromedriver

现在,在PyCharm中输入以下代码,Chrome浏览器就会自动打开https://www.baidu.com

from selenium import webdriver

driver = webdriver.Chrome()
url = 'https://www.baidu.com'
driver.get(url)

参考资料:

  1. mac +selenium+python 环境搭建问题
  2. Mac OS环境配置chromedriver
  3. selenium 安装与 chromedriver安装
  4. 通过chmod改变文件权限