这里的selenium使用的版本为3.141.0,安装时使用命令 pip install selenium==3.141.0
元素定位
image.png这些都有对应的复数形式,如find_elements_by_id等,他们会将符合匹配要求的全部元素以list返回。
还可以以get_element(self, by=By.ID, value=None)来获取各种元素,第二个参数默认是By.ID,也可改为By.XPATH,By.NAME等,如:
from selenium import webdriver
from selenium.webdriver.common.by import By
def get_element(driver,*loc):
e = driver.find_element(*loc)
return e
if __name__ == '__main__':
driver = webdriver.Chrome()
driver.get('http://www.baidu.com/')
get_element(driver,By.ID,'kw').send_keys('selenium')
get_element(driver,By.XPATH,'//*[@id="su"]').click()
WebDriver属性
常用属性有如下:
image.png
from selenium import webdriver
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://www.baidu.com')
self.driver.maximize_window()
def test_prop(self):
print(self.driver.name) # 浏览器名称
print(self.driver.current_url)
print(self.driver.title)
print(self.driver.window_handles)
print(self.driver.page_source)
self.driver.quit()
def test_method(self):
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
sleep(2)
self.driver.back()
sleep(2)
self.driver.refresh()
sleep(2)
self.driver.forward()
if __name__ == '__main__':
case = TestCase()
case.test_method()
WebElement属性和方法
属性方法
from selenium import webdriver
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://sahitest.com/demo/linkTest.htm')
def test_webelement_prop(self):
e = self.driver.find_element_by_id('t1')
print(type(e))
print(e.id)
print(e.tag_name)
print(e.size)
print(e.rect)
print(e.text)
def test_webelement_method(self):
e = self.driver.find_element_by_id('t1')
e.send_keys('hello world')
sleep(2)
print(e.get_attribute('type'))
print(e.get_attribute('name'))
print(e.value_of_css_property('font'))
print(e.value_of_css_property('color'))
sleep(2)
e.clear()
if __name__ == '__main__':
case = TestCase()
# case.test_webelement_prop()
case.test_webelement_method()
------------------输出----------------
text
normal normal 400 normal 13.3333px / normal Arial
rgba(0, 0, 0, 1)
操作form表单
首先在py文件的同级目录中创建forms.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="javascript:alert('hello')">
Username:<input type="text" name="username" id="username"><br>
Password:<input type="password" name="pwd" id="pwd"><br>
<input type="submit" value="submit" id="submit">
</form>
</body>
</html>
在demo.py中进行操作
from selenium import webdriver
import os
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/forms.html'
print(file_path)
self.driver.get(file_path)
def test_login(self):
username = self.driver.find_element_by_id('username')
username.send_keys('admin')
pwd = self.driver.find_element_by_id('pwd') # 定位表单元素
pwd.send_keys('123') # 输出测试值
print(username.get_attribute('value')) # 输出表单元素属性
print(pwd.get_attribute('value'))
sleep(2)
self.driver.find_element_by_id('submit').click() # 表单提交
self.driver.switch_to.alert.accept() # 点击确认
pwd.clear()
username.clear()
if __name__ == '__main__':
case = TestCase()
case.test_login()
操作checkoutbox多选框和radiobutton单选框
首先创建forms2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="javascript:alert('test')"></form>
swimming:<input type="checkbox" name="swimming" value="swimming"><br>
reading:<input type="checkbox" name="reading" value="reading"><br>
<hr>
gender:<input type="radio" name="gender" value="male"><br>
<input type="radio" name="gender" value="female"><br>
<input type="submit" value="Login">
</body>
</html>
在同级目录下创建py文件
from selenium import webdriver
from time import sleep
import os
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/forms2.html'
self.driver.get(file_path)
def test_checkbox(self):
swimming = self.driver.find_element_by_name('swimming')
if not swimming.is_selected(): # 判断是否选中
swimming.click()
reading = self.driver.find_element_by_name('reading')
if not reading.is_selected():
reading.click()
sleep(3)
swimming.click()
sleep(3)
self.driver.quit()
def test_radio(self):
lst = self.driver.find_elements_by_name('gender')
lst[1].click()
if __name__ == '__main__':
case = TestCase()
# case.test_checkbox()
case.test_radio()
操作下拉列表
需要用到select工具类,其常用方法如下:
image.png
先创建forms3.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="javascript:alert('test')">
provide:
<select name="provise" id="provise">
<option value="bj">Beijing</option>
<option value="tj">Tianjin</option>
<option value="sh">Shanghai</option>
</select>
</form>
</body>
</html>
创建测试文件
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.support.select import Select
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/form3.html'
self.driver.get(file_path)
def test_select(self):
se = self.driver.find_element_by_id('provise')
select = Select(se) # 实例化Select工具类
select.select_by_index(2) # 根据索引选择
sleep(2)
select.select_by_value('bj') # 根据值选择
sleep(2)
select.select_by_visible_text('Tianjin') # 根据文本选择
sleep(2)
for i in range(3): # 依次全选
select.select_by_index(i)
sleep(1)
sleep(3)
for option in select.options:
print(option.text)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test_select()
selenium处理弹窗
弹窗有三种
- alert: 用来提示
- confirm:用来确认
-
prompt:输入内容
image.png
创建test_alert.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="javascript:alert('提示框')" id="alert">Alert</a><br>
<a href="javascript:confirm('真的要删除数据吗')" id="confirm">Confirm</a><br>
<a href="javascript:var age = prompt('请输入年龄');document.write(age)" id="prompt">Prompt</a><br>
</body>
</html>
再创建测试文件
from selenium import webdriver
from time import sleep
import os
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
path = os.path.dirname(os.path.abspath(__file__))
file_path = 'file:///'+path+'/test_alert.html'
self.driver.get(file_path)
def test_alert(self):
self.driver.find_element_by_id('alert').click()
# 切换到alert
alert = self.driver.switch_to_alert()
print(alert.text)
sleep(3)
alert.accept()
def test_confirm(self):
self.driver.find_element_by_id('confirm').click()
confirm = self.driver.switch_to_alert()
print(confirm.text)
# confirm.accept()
sleep(2)
confirm.dismiss()
def test_prompt(self):
self.driver.find_element_by_id('prompt').click()
prompt = self.driver.switch_to_alert()
print(prompt.text)
sleep(1)
prompt.send_keys('20')
sleep(2)
prompt.accept()
self.driver.find_elements_by_id()
if __name__ == '__main__':
case = TestCase()
# case.test_alert()
# case.test_confirm()
case.test_prompt()
selenium三种等待方式
- time.sleep 固定等待最不建议,会导致自动化时间无限延长
- implicitly_wait 隐式等待:通过设定的时长等待页面元素加载完成,再执行下面的代码,如果超过设定时间还未加载完成,则继续执行下面的代码(注意:在设定时间内加载完成则立即执行下面的代码),隐式等待对于整个driver周期都起作用,只需要在最开始设置一次即可
-
WebDriverWait 显示等待:等待某个条件成立时继续执行,WebDriverWait 中的参数如下,他还有两种方法until与until_not
参数
方法中的参数
举个例子
from selenium import webdriver
from time import sleep
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Testcase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://www.baidu.com')
# sleep(2)
def test_sleep(self):
self.driver.find_element_by_id('kw').send_keys('selenium')
sleep(2) # 线程阻塞
self.driver.find_element_by_id('su').click()
sleep(3)
self.driver.quit()
def test_implicitly(self):
self.driver.implicitly_wait(10)
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
self.driver.quit()
def test_wait(self):
wait = WebDriverWait(self.driver,2)
wait.until(EC.title_is('百度一下,你就知道'))
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
self.driver.quit()
if __name__ == '__main__':
case = Testcase()
case.test_implicitly()
selenium等待条件
image.png举个例子,先创建test_wait.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- timeout-->
</head>
<body>
<script>
function f() {
window.setTimeout("populate()",2000);
}
function populate(){
document.f1.t1.value = "populated";
document.getElementById("id1").innerHTML = "<div id='id2'>id 2</div>"
}
</script>
<form name="f1">
<input type="text" name="t1">
<input type="button" value="Click me" onclick="f()" id="btn">
<div id="id1">
</div>
</form>
</body>
</html>
同级目录下创建py文件
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
'''
test_wait.html这个html是有一个按键和文本框,按下按键两秒后文本框出现内容
'''
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
file_path = 'file:///'+os.path.abspath('test_wait.html')
self.driver.get(file_path)
def test(self):
self.driver.find_element_by_id('btn').click()
# 显式等待
wait = WebDriverWait(self.driver,3) # 这里等待时间从3改为1会返回超时的异常
wait.until(EC.text_to_be_present_in_element((By.ID,'id2'),'id 2'))
self.driver.find_element_by_id('id2').text
print('ok')
if __name__ == '__main__':
case = TestCase()
case.test()
鼠标键盘事件
selenium中的鼠标和键盘事件被封装在ActionChains类中,正确的使用方法是:ActionChains(driver).click(btn).perform()
image.png
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
def test_mouse(self):
self.driver.get('http://sahitest.com/demo/clicks.htm')
btn = self.driver.find_element_by_xpath('/html/body/form/input[2]')
ActionChains(self.driver).double_click(btn).perform()
sleep(2)
btn2 = self.driver.find_element_by_xpath('/html/body/form/input[3]')
ActionChains(self.driver).click(btn2).perform()
sleep(2)
btn3 = self.driver.find_element_by_xpath('/html/body/form/input[4]')
ActionChains(self.driver).context_click(btn3).perform()
def test_key(self):
self.driver.get('http://www.baidu.com')
# kw = self.driver.find_element_by_id('kw')
# kw.send_keys('selenium')
# kw.send_keys(Keys.CONTROL,'a')
# sleep(2)
# kw.send_keys(Keys.CONTROL,'x')
# sleep(2)
# kw.send_keys(Keys.CONTROL,'v')
# sleep(2)
e = self.driver.find_element_by_link_text('新闻')
ActionChains(self.driver).move_to_element(e).perform()
sleep(2)
if __name__ == '__main__':
case = TestCase()
# case.test_mouse()
case.test_key()
selenium执行javascript脚本
- execute_script同步执行
- execute_asunc异步执行
from selenium import webdriver
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.get('http://www.baidu.com')
def test1(self):
self.driver.execute_script("alert('test')")
sleep(2)
self.driver.switch_to.alert.accept()
def test2(self):
js = 'return document.title'
title = self.driver.execute_script(js)
print(title)
def test3(self):
js = 'var q = document.getElementById("kw"); q.style.border="2px solid red"'
self.driver.execute_script(js)
def test4(self):
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
sleep(2)
js = 'window.scrollTo(0, document.body.scrollHeight)' # 将滚动滚到底
self.driver.execute_script(js)
sleep(2)
if __name__ == '__main__':
case = TestCase()
case.test4()
selenium屏幕截屏
from selenium import webdriver
from time import sleep, strftime, localtime, time
import os
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.get('http://www.baidu.com')
def test1(self):
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
sleep(2)
st = strftime("%Y-%m-%d-%H-%M-%S", localtime(time()))
fime_name = st + '.png'
path = os.path.abspath('screenshot')
file_name = path+'/'+fime_name
self.driver.get_screenshot_as_file(file_name)
if __name__ == '__main__':
case = TestCase()
case.test1()
selenium定位frame iframe
frame标签有frameset、frame、iframe三种,frameset跟其他普通标签没有区别,不会影响到正常的定位,而frame与iframe对selenium定位而言是一样的,selenium有一组方法对frame进行操作。
image.png
from selenium import webdriver
from time import sleep
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://sahitest.com/demo/framesTest.htm')
def test1(self):
top = self.driver.find_element_by_name('top')
self.driver.switch_to_frame(top) # 切换frame
self.driver.find_element_by_xpath('/html/body/table/tbody/tr/td[1]/a[1]').click()
self.driver.switch_to.default_content() # 返回主frame
sleep(3)
second = self.driver.find_element_by_xpath('/html/frameset/frame[2]')
self.driver.switch_to.frame(second)
self.driver.find_element_by_xpath('/html/body/table/tbody/tr/td[1]/a[2]').click()
sleep(3)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test1()
网友评论