Selenium环境搭建

1. 安装Python
2. 安装基于Python的Selenium包
  1. 新建一个专门放置脚本的目录:D:/Python/Scripts
  2. 输入命令pip install selenium
    这里有可能报错,加--user即可:pip install selenium --user
  3. pip show selenium查看版本看是否安装成功
3. 运行自动化脚本
  1. 在本地建一个test.py的脚本文件,里面写个简单的自动化脚本,如下:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

driver.find_element_by_id("kw").send_keys("selenium2")
driver.find_element_by_id("su").click()
# driver.quit()
  1. 在cmd下运行该脚本python test.py
    发现会报错,报错信息如下:
 Traceback (most recent call last):
  File "C:\Users\Pillar_it3\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)
  File "C:\Program Files\Python37\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Program Files\Python37\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 3, in 
    driver = webdriver.Chrome()
  File "C:\Users\Pillar_it3\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\Pillar_it3\AppData\Roaming\Python\Python37\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

原因是缺少chrome的一个驱动文件。

4. 下载并安装浏览器驱动

chrome下载地址:
https://sites.google.com/a/chromium.org/chromedriver/home

Firefox的geckodriver下载地址:
https://github.com/mozilla/geckodriver/releases

查看本地的chrome版本,然后下载对应的驱动。
下载完成后本地解压,把exe文件拷贝到python的安装目录下:


python安装目录.png

我本地至此就可以通过python test.py跑起来了

你可能感兴趣的:(Selenium环境搭建)