一、介绍
Selenium是一个用于测试网站的自动化测试工具,支持各种浏览器包括Chrome、Firefox、Safari等主流界面浏览器,同时也支持phantomJS无界面浏览器
官方API文档:http://seleniumhq.github.io/selenium/docs/api/py/api.html
二、环境安装
1、安装库
2、下载chromedriver : 登录http://chromedriver.storage.googleapis.com/index.html 下载 (与浏览器对应版本请上网查阅)
对应版本查看,以谷歌浏览器为例
打开浏览器,按F12,点击console
navigator.appCodeName
navigator.appVersion
navigator.userAgent
按F12,点击console,输入以下命令,可以看到为102.0.5005.115版本
下载后将chromedriver.exe文件放至 python.exe所在目录 如: D:\Program Files\Python
至此,环境安装完成
三、编写代码
搜索框定位
百度搜索按钮定位
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
import os
from selenium import webdriver
# 实例化浏览器
driver = webdriver.Chrome()
# 打开网址
driver.get('https://www.baidu.com/')
# 需求
driver.find_element(By.ID,"kw").send_keys('锅锅')
driver.find_element(By.ID, "su").click()#点击按钮
sleep(2)
# 关闭页面
driver.quit()