[Mac] selenium打开Chrome浏览器
在Mac电脑用python+selenium打开Chrome还遇到几个问题,这里总结下,以防忘记,也可帮到别人。
前提:已安装好python3,selenium
安装chromedriver
1.先查看Chrome的版本,我这里是87
- 下载与Chrome浏览器对应的chromedriver版本,下载链接:
https://sites.google.com/a/chromium.org/chromedriver/downloads 把下载的文件解压,把chromedriver.exe拷到/usr/local/bin/下。
- 打开Finder,Ctrl+Shift+G, 输入/usr/local/bin/ 回车,进入到该目录
- 把chromedriver.exe复制进来
4.添加chromedriver.exe到环境变量 - 打开命令行终端,输入vim ~/.bash_profile
- 添加一行:export PATH=$PATH:/usr/local/bin/chromedriver,保存并退出
- 执行source ~/.bash_profile,让修改生效
代码
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
如果你的Chrome安装在默认路径,这时运行代码没有问题。但是我运行的时候报错:
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
研究发现是我的Chrome没有安装在默认路径下,所以需要在代码里指明Chrome的路径,这里也可以再指明一次chromedriver.exe的路径,代码如下:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.binary_location='/Google Chrome.app/Contents/MacOS/Google Chrome' # Chrome path
chrome_driver_binary = "/usr/local/bin/chromedriver" # chromedriver path
driver = webdriver.Chrome(chrome_driver_binary,chrome_options=options)
driver.maximize_window()
driver.get("http://www.baidu.com")
还没有评论,来说两句吧...