环境准备
安装selenium:pip install selenium
示例
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() # 启动 Chrome 浏览器
driver.get("http://www.jeasyui.com/index.php") # 访问 EasyUI 首页
time.sleep(1) # 停留 1 秒时间
demo_nav = driver.find_element(By.LINK_TEXT, 'Demo') # 通过链接文本定位元素,在此定位的是导航栏中的 Demo 菜单
demo_nav.click() # 点击导航栏中的 Demo 菜单
time.sleep(10) # 停留 10 秒时间
driver.quit() # 关闭浏览器
Webdriver:
1. 元素查找
2.元素定位
2.1 id定位:id具有唯一性,如果元素的属性值是动态的,则尽量不使用id定位。
初始化浏览器对象:
from selenium.webdriver.chrome.service import Service
service = Service(executable_path= r'D:\yang\chromedriver.exe')
driver = webdriver.Chrome(service=service)
2.2 访问页面
get()方法
driver = webdriver.Chrome()
driver.get("http://www.jeayui.com/index.php")
切换浏览器标签页:
selenium提供了 switch_to.window(handle)方法切换浏览器标签页
参数handle为标签页句柄
current_window_handle:获得当前标签页句柄
window_handles:获取所有的标签页句柄
浏览器弹窗操作
浏览器弹窗有alert,confirm,prompt三种形式,属于浏览层结构,不能通过页面元素定位操作。
先通过switch_to.alert()方法先切换弹窗,然后使用accept(),dismiss(), text,send_keys(keysToSend)方法进行相关操作
accept(),接受弹窗信息
dismiss(), 取消弹窗
text,获取弹窗中的文本内容
send_keys(keysToSend) 发送内容,对有提交需求的prompt提示消息框
页面元素定位
定位方式 | By.*定位 | find_element_by_*定位 |
id定位 | find_element(By.ID,value) | find_element_by_id(value) |
name定位 | find_element(By.NAME,value) | find_element_by_name(value) |
class定位 | find_element(By.CLASS_NAME,value) | find_element_by_class_name(value) |
tag定位 | find_element(By.TAG_NAME,value) | find_element_by_tag_name(value) |
link定位 | find_element(By.LINK_TEXT,value) | find_element_by_link_text(value) |
partial link定位 | find_element(By.PARTIAL_LINK_TEXT,value) | find_element_by_partial_link(value) |
css定位 | find_element(By.CSS_SELECTOR,value) | find_element_by_css_selector(value) |
xpath定位 | find_element(By.XPATH,value) | find_element_by_xpath(value) |
绝对定位
相对定位
文本定位:
结合关键字contains一起使用,//a[contains(text(),"Dem")]
逻辑运算定位
and or
driver.find_element(By.XPATH, "//a[@src='/image/logo2.png' and @alt='JQuery EasyUI']"
通配符匹配
//a[@*='JQuery EasyUI'] 表示a标签中含有属性值是JQuery EasyUI的元素,不用考虑属性名
关系匹配
例如 通过LOGO图片的父节点定位的LOGO图片,则XPath表达式可写成//*[@id="elogo"]/ul/li/a/child::img[1]
-
child 选取当前节点的所有子节点
-
parent 选取当前节点的父节点
-
descendant 选取当前节点的所有后代节点
-
ancestor 选择当前节点的所有先辈节点
-
descendant-or-self 选取当前节点的所有后代节点及其当前节点本身
-
ancestor-or-self 选取当前节点所有先辈节点及当前节点本身
-
preceding-sibling 选取当前节点之前的所有同级节点
-
following-sibling 选取当前节点之后的所有同级节点
-
preceding 选取当前节点的开始标签之前的所有节点
-
following 选取当前节点的开始标签之后的所有节点
not 排除
相对定位
above below to_left_of to_right_of near
获取当前页面的源码
source = driver.page.source
获取Title文本
title = driver.title
获取当前URL
url = driver.current_url
获取元素属性值
get_attribute(name)
获取元素的其他属性
id:获取元素id
location:获取元素的位置
size:获取元素大小
tag_name 获取元素标签
is_displayed() 判断元素的显示状态
is_selected()判断Radio Box,Check Box元素的选中状态 如果选择返回True
is_enabled()判断input select等标签元素的编辑状态,如果可编辑,返回true
页面元素操作
单击 click()
输入文本 send_keys(value)
清除文本clear()
提交表单submit()
下拉框操作;如果是select开发的下拉框,可直接使用Selenium提供的Select类进行操作。
from selenium.webdriver.support.ui import Select
Frame结构操作
switch_to.frame(index):通过frame的索引index切换到对应的frame
switch_to.frame(name):
switch_to.frame(webelement):
switch_to.default_content():退出frame结构,切换到主HTML页面中
switch_to.parent_frame(): 切换到父级frame结构
文件操作
文件上传操作分为直接上传和借助外力上传,
1 直接上传:使用selenium的send_key()方法
2 借助外力:将遮盖或隐藏的input[type='file']显露出来,再使用send_key()方法上传
文件下载:
download.default_directory 设置下载路径
download.prompt_for_download设置下载时是否弹出下载提示框
模拟鼠标操作:
from selenium.webdriver.common.action_chains import ActionChains
导入ActionChains类
demo_nav = driver.find_element(By.LINK_TEXT, 'Demo')
action = ActionChains(driver) 实例化ActionChains
action.click(demo_nav) 钓鱼鼠标操作方法
action.perform() 执行鼠标操作
单击 action.click
右键单击 context_click()
左键双击 double_click()
悬停 move_to_element()
拖曳 drag_and_drop(source,target)
模拟键盘操作
from selenium.webdriver.common.keys import Keys
延时等待
强制等待
from time import sleep
sleep(3)
隐式等待: 使用的是selenium提供的 implicitly_wait(time_to_wait)方法
driver = webdriver.Chrome()
driver.implicitly_wait(10)
显示等待:使用的是selenium提供的WebDriverWait(driver,timeout,poll_frequency=POLL_FREQUENCY,ignored_exceptions=None)类
driver:为实例化的webdriver对象
timeout为超时时间
poll_frequency为调用频率
ignored_exceptions:忽略参数
默认值POLL_FREQUENCY 0.5s
WebdriverWait()类下有until(method,message=")和until_not(method,message=") 2个方法
浏览器配置
以Chrome浏览器ChromeOptions为例
设置默认编码格式为UTF-8
options = webdriver.ChromeOptions()
options.add_argument('lang=zh_CN.UTF-8')
driver = webdriver.Chrome(options=options)
其他如调用JavaScript
Cookies操作
屏幕截图
获取环境信息:使用capabilities属性
driver = webdriverChrome()
print(driver.capabilities(["timeouts"])
执行CDP命令
selenium1