1、搭建环境
1)安装python3+selenium
brew install python3
pip3 install selenium(安装最新版) 或 pip3 install selenium==版本号(安装指定版本号)
没有特殊要求安装最新版即可
2)下载chrome浏览器和chromedriver
chromedriver下载地址:http://chromedriver.storage.googleapis.com/index.html
需根据chrome版本选择对应chromedriver
3)chromedriver路径
默认放在 /usr/local/bin路径下,在此路径创建driver对象不需要指定chromedriver驱动路径,
直接chrome_driver = webdriver.Chrome()即可
若放在其他路径下,需要指定chromedriver驱动路径,chromedriver_path = 'xxxxxxxx/chromedriver',
chrome_driver = webdriver.Chrome(executable_path=chromedriver_path)
2、基本使用
1)元素定位
id
class
link_text
partial_link_text
tag
name
xpath
css
2)元素基本操作
click:点击
例:chrome_driver.find_element_by_link_text('快讯').click()
send_keys:输入内容、上传文件
例:search_input_xpath = '/html/body/div[2]/div/div/div[2]/input'
chrome_driver.find_element_by_xpath(search_input_xpath).send_keys('search content')
text:获取文本
例:first_hot_tag_xpath = '/html/body/div[2]/div/div/div[3]/ul/li[1]/a'
text = chrome_driver.find_element_by_xpath(first_hot_tag_xpath).text
ActionChains:鼠标相关操作
例:from selenium.webdriver.common.action_chains import ActionChains
media_project_xpath = '//*[@id="app"]/div/div[1]/div[1]/div/div/div[4]/ul/li[1]/div[2]/span'
ele = chrome_driver.find_element_by_xpath(media_project_xpath)
ActionChains(chrome_driver).move_to_element(ele).perform()
perform:悬停
click:点击
double_click:双击
click_and_hold:按住不动
...
等等
implicitly_wait:隐式等待
implicitly_wait(5):5秒内找到元素就执行,不一定是5秒,超过5秒报异常(使用这个经常报错)
sleep(5):等待5秒
switch_to:切换
switch_to.window:切换窗口
例:chrome_driver.switch_to.window(chrome_driver.window_handles[1])
switch_to.frame:切换到frame
switch_to.alert:切换到alert弹窗
current
chrome_driver.current_url:当前页url
chrome_driver.current_window_handle:当前页窗口
back/refresh/forward
chrome_driver.back():后退
chrome_driver.refresh():刷新
chrome_driver.forward():前进
save_screenshot:截图
chrome_driver.save_screenshot(路径+名称)
execute_script:js相关
js = 'window.scrollTo(0,document.body.scrollHeight)'
chrome_driver.execute_script(js) #滑到页面底部
Select:select选择框
from selenium.webdriver.support.select import Select
select标签专用