1.需要先安装selenium包
pip install selenium # Windows电脑安装selenium
pip3 install selenium # Mac电脑安装selenium
2.下载谷歌浏览器驱动
打开chrome浏览器,在网址栏中输入chrome://version/打开关于版本页面,根据版本信息下载相应chrome驱动
下载地址:https://chromedriver.storage.googleapis.com/index.html
下载后解压缩得到:chromedriver.exe
3.将浏览器驱动放到谷歌安装位置:
C:\ProgramFiles\Google\Chrome\Application
4.将浏览器驱动放到python解释器位置:
\Python\Scripts
5.将chrome浏览器安装路径添加到path环境变量
6.测试1-5步骤是否成功:
6.1新建.py文件,代码:
from selenium import webdriver
driver = webdriver.Chrome()
#引入selenium库中的 webdriver 模块
from selenium import webdriver
#引入time库
import time
#打开谷歌浏览器
driver = webdriver.Chrome()
#打开微博
driver.get('https://weibo.com/login.php')
#给睡眠时间防止网速慢打不开网页
time.sleep(20)
#全屏浏览器
driver.maximize_window()
#在主页面点击登录按钮,进入登录页面
#driver.find_element_by_xpath('//*[@id="notLogin"]/span/a[1]').click()
#输入账号和密码
driver.find_element_by_xpath('//*[@id="loginname"]').send_keys('name')
driver.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input').send_keys('passwd')
#点击登录按钮
driver.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[6]/a/span').click()