我想在Mac上使用selenium和chromedriver,但我遇到了一些问题。
- 我从ChromeDriver - WebDriver for Chrome下载了chromedriver。
- 但我不想将它放到PATH中,所以我这样做。
import os
from selenium import webdriver
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DRIVER_BIN = os.path.join(PROJECT_ROOT, "bin/chromedriver_for_mac")
print DRIVER_BIN
browser = webdriver.Chrome(DRIVER_BIN)
browser.get('http://www.baidu.com/')
但是我无法得到我想要的结果。
Traceback (most recent call last):
File "/Users/wyx/project/python-scraping/se/test.py", line 15, in <module>
browser = webdriver.Chrome(DRIVER_BIN)
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver_for_mac' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x107f96150>> ignored
然后我运行
brew cask install chromedriver
。并且我只运行它而不需要指定驱动程序路径。
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
但这也行不通。
Traceback (most recent call last):
File "/Users/wyx/project/python-scraping/se/test.py", line 16, in <module>
browser = webdriver.Chrome()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x105c08150>> ignored
Process finished with exit code 1
最后我试着把它放到/usr/bin目录下
➜ Downloads sudo cp chromedriver /usr/bin
Password:
cp: /usr/bin/chromedriver: Operation not permitted
我尝试在.zshrc中使用export PATH=$PATH:/Users/wyx/project/python-scraping/se/bin/chromedriver_for_mac
,但是出现了以下错误:
selenium.common.exceptions.WebDriverException: Message: 'chromedriver'可执行文件需要在PATH中。
那么如何解决呢?我想使用不在PATH中的驱动程序路径,以便可以轻松部署我的项目。
解决方案:
brew cask install chromedriver
which chromedriver
获取驱动程序路径- 然后像这样使用:
webdriver.Chrome("/usr/local/bin/chromedriver")
但我不知道为什么要使用selenium如此复杂。
brew install chromedriver --cask
的安装位置为/opt/homebrew/bin/chromedriver
。 - james-see