1、Selenium安装
pip3 install selenium chromedriver_installer
2、编辑我的第一个测试脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A very basic selenium example."""
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
browser.quit()
3、首次运行报错
调用chrome报错信息:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 76, in start
stdin=PIPE)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1499, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver': 'chromedriver'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test1.py", line 8, in
browser = webdriver.Chrome()
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
self.service.start()
File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 83, 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
意思是说没有找到chromedriver,或者不在PATH中。
换成调用Firefox也会有类似的报错信息:
FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver': 'geckodriver'
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
在网上查了一下,有很多人都遇到了这个问题,这确实是学习selenium的第一个拦路虎,第一关就过不去。
4、解决办法
直接用brew安装chromedriver
brew install chromedriver
等了半天没有反应,因为chrome是那谁家的,在这里克服第二关,你会看到:
提示:
Error: No available formula with the name "chromedriver"
It was migrated from homebrew/core to homebrew/cask.
You can access it again by running:
brew tap homebrew/cask
And then you can install it by running:
brew cask install chromedriver
按照提示再次输入:
brew tap homebrew/cask
brew cask install chromedriver
chromedriver was successfully installed!
搞定了Chrome,再装Firefox所需的geckodriver
brew install geckodriver
5、运行通过
再次运行脚本,可以正常的看到chrome打开了百度,执行了搜索,最后关闭了浏览器。