安装配置Selenium及Pythonwebdriver环境搭建
准备工具如下:
python安装包:https://www.python.org/getit/
PyCharm 安装包:http://www.jetbrains.com/pycharm/download/
Selenium安装包:https://pypi.python.org/pypi/selenium
一:安装python包,选择全部组件(勾选pip、安装过程中配置环境变量)
安装selenium方式一:pip install -U selenium
联网安装Selenium (在pycharm路径cmd)
方式二:解压selenium-3.13.0.tar.gz,然后用cmd进入解压目录,使用命令 Python setup.py install 安装Selenium
二。安装驱动
Chromedriver http://npm.taobao.org/mirrors/chromedriver/ 谷歌浏览器
Geckodriver https://github.com/mozilla/geckodriver/releases 火狐
IEDriverServer http://selenium-release.storage.googleapis.com/index.html ie浏览器
MicrosoftWebDriver https://developer.microsoft.com/en-us/microsoft-edge/tools/ webdriver/ 微软自带edge
下载对应浏览器对应版本驱动,解压后有两种配置方式:(以谷歌为例)
配置方式一: 把下载好的chromedriver.exe程序放置到python的安装路径下 (我用的)
在cmd中path 可以看到python路径
我的路径:C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32
记住webdriver的驱动要存放在python的安装目录下,也就是放在python.exe同一级目录,要不然你会打不开浏览器的。
配置方式二: 1)把下载好的chromedriver.exe程序放置到python项目中(其它路径也可) 2)在python中代码编写如下即可: chromePath = chromedriver.exe路径 os.environ[‘webdriver.chrome.driver’] = chromePath # gecko ie等 driver = webdriver.Chrome(executable_path=chromePath) # Firefox、Ie等
三、打开pycharm,install selenium
新建一个工程,在工程下新建一个包,包名随意。
选中包,依次点击:
开始时没有红框中的两个,点击右边的+,在搜索框内输入selenium,
点击install package
安装成功、
前图中红框内容会出现。
四、导包使用
新建一个py文件(不能为selenium,因为接最后需要写代码导入selenium包,而一个py文件就是一个包,如果命名为selenium,就会导入自己的文件,自己文件没有需要导入的模块,报错)
写入以下代码:
from selenium import webdriver
import time
driver = webdriver.Chrome() ####driver是对象名,可以随意,如果火狐,就是.Firefox() 同理,ie 就是 .Ie(), edge是.Edge()
driver.get("http://www.baidu.com") ##实验能否自动打开这个网页
time.sleep(5)
driver.quit() ##退出