一.项目目录 二.各种html文件
1.actionselect.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作下拉列表</title>
</head>
<body>
<select name="fruit" size="1">
<option id="peach" value="taozi">桃子</option>
<option id="watermelon" value="xigua">西瓜</option>
<option id="orange" value="juzi" selected="selected">橘子</option>
<option id="kiwifruit" value="nihoutao">猕猴桃</option>
<option id="maybush" value="shanzha">山楂</option>
<option id="litchi" value="lizhi">荔枝</option>
</select>
</body>
</html>
2.checkbox.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作复选框</title>
</head>
<body>
<form name="form1">
<input type="checkbox" name="fruit" value="berry" />草莓</input>
<input type="checkbox" name="fruit" value="watermelon" />西瓜</input>
<input type="checkbox" name="fruit" value="orange" />橙子</input>
</form>
</body>
</html>
3.doubleclick.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模拟鼠标双击操作</title>
</head>
<body>
<input id="inputBox" type="text" ondblclick="javascript:this.style.background='red'">请双击</>
</body>
</html>
4.inputselect.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作可输入下拉列表,输入的同时模拟按键</title>
</head>
<body>
<div style="position:relative;">
<input list="pasta" id="select">
<datalist id="pasta">
<option>Bavette</option>
<option>Rigatoni</option>
<option>Fiorentine</option>
<option>Gnocchi</option>
<option>Tagliatelle</option>
<option>Penne lisce</option>
<option>Pici</option>
<option>Pappardelle</option>
<option>Spaghetti</option>
<option>Cannelloni</option>
<option>Cancl</option>
</datalist>
</div>
</body>
</html>
5.isdisplay.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML中显示与隐藏元素</title>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<script type="text/javascript">
function showAndHidden1() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
if(div1.style.display=='block') div1.style.display='none';
else div1.style.display='block';
if(div2.style.display=='block') div2.style.display='none';
else div2.style.display='block';
}
function showAndHidden2() {
var div3 = document.getElementById("div3");
var div4 = document.getElementById("div4");
if(div3.style.visibility=='visible') div3.style.visibility='hidden';
else div3.style.visibility='visible';
if(div4.style.visibility=='visible') div4.style.visibility='hidden';
else div4.style.visibility='visible';
}
</script>
</head>
<body>
<div>display:元素不占用页面位置</div>
<div id="div1" style="display: block;">DIV 1</div>
<div id="div2" style="display: none;">DIV 2</div>
<input id="button1" type="button" onclick="showAndHidden1();" value="DIV切换" />
<hr>
<div>visibility:元素占用页面位置</div>
<div id="div3" style="visibility: visible;">DIV 1</div>
<div id="div4" style="visibility: hidden;">DIV 2</div>
<input id="button2" type="button" onclick="showAndHidden2();" value="DIV切换" />
</body>
</html>
6.isenable.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"/>
<title>HTML 中不可操作元素</title>
</head>
<body>
<input id="input1" type="text" size="40" value="可操作">
<br />
<input id="input2" type="text" size="40" value="不可用" disabled>
<br />
<input id="input3" type="text" size="40" value="只读" readonly>
</body>
</html>
7.multipleOptions.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作多选列表</title>
</head>
<body>
<select name="fruit" size="6" multiple=true>
<option id="peach" value="taozi">桃子</option>
<option id="watermelon" value="xigua">西瓜</option>
<option id="orange" value="juzi">橘子</option>
<option id="kiwifruit" value="nihoutao">猕猴桃</option>
<option id="maybush" value="shanzha">山楂</option>
<option id="litchi" value="lizhi">荔枝</option>
</select>
</body>
</html>
8.radio.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作单选框</title>
</head>
<body>
<form>
<input type="radio" name="fruit" value="berry" />草莓</input>
<br />
<input type="radio" name="fruit" value="watermelon" />西瓜</input>
<br />
<input type="radio" name="fruit" value="orange" />橙子</input>
</form>
</body>
</html>
9.titleWindow.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用title属性识别和操作新弹出的浏览器窗口</title>
</head>
<body>
<p id = 'p1'>title属性识别</p>
<br><br>
<a href="http://www.sogou.com" target="_blank">sogou 搜索</a>
</body>
</html>
10.uploadfile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="parse_file.jsp" mothod="post">
<p>Browse for a file to upload:</p>
<input id="file" name="file" type="file">
</input>
<br/><br/>
<input type="submit" id="filesubmit" value="SUBMIT">
</input>
</form>
</body>
</html>
11.frameset.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>frameset 页面</title>
</head>
<frameset cols="25%,50%,25%">
<frame id="leftframe" src="frame_left.html" />
<frame id="middleframe" src="frame_middle.html" />
<frame id="rightframe" src="frame_right.html" />
</frameset>
</html>
二.实例
1.WebdriverApi基础实例
from selenium import webdriver
import unittest
import time
''' 常用webdriverApi详解(基础部分)'''
class MyTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
def testOpenBaiduUrl(self):
'''
1.访问具体地址
:return:
'''
baseUrl = 'https://www.baidu.com/'
baseTitle = u'百度一下'
self.driver.get(baseUrl)
currTitle = self.driver.title
self.assertIn(baseTitle, currTitle, msg=u'页面跳转失败')
def testBackForwardRefresh(self):
'''
前进,后退,刷新当前页面
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
baseSogouUrl = 'https://www.sogou.com/'
self.driver.get(baseBaiduUrl)
self.driver.get(baseSogouUrl)
self.driver.back()
self.assertIn(self.driver.current_url, baseBaiduUrl, msg=u'百度地址访问错误')
print(self.driver.current_url)
self.driver.forward()
self.assertIn(self.driver.current_url, baseSogouUrl, msg=u'搜狗地址访问错误')
print(self.driver.current_url)
if self.driver.current_url == baseBaiduUrl:
self.driver.find_element_by_id('kw').send_keys('baidu')
else:
self.driver.find_element_by_id('query').send_keys('sogou')
self.driver.refresh()
def testWindow(self):
'''
窗口最大化,获取当前窗口的位置,设置当前窗口的位置
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
position = self.driver.get_window_position()
print(u'当前窗口的横坐标为{}'.format(position['x']))
print(u'当前窗口的纵坐标为{}'.format(position['y']))
self.driver.set_window_position(400, 200)
print(u'设置后的窗口的位置坐标:{}'.format(self.driver.get_window_position()))
self.driver.maximize_window()
def testWindowSize(self):
'''
获取当前窗口的大小,设置当前窗口的大小
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
windowSize = self.driver.get_window_size('current')
print(u'当前窗口的宽为{}'.format(windowSize['width']))
print(u'当前窗口的高为{}'.format(windowSize['height']))
self.driver.set_window_size(width=200, height=400, windowHandle='current')
print(self.driver.get_window_size('current'))
def testGetBaiduTitle(self):
'''
获取页面的title属性值
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
bdTitle = self.driver.title
print(bdTitle)
self.assertEqual(bdTitle,u'百度一下,你就知道',msg=u'页面title不正确')
def testGetBaiduUrlSourceCode(self):
'''
获取页面的url和页面源码
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
bdUrl = self.driver.current_url
print(bdUrl)
self.assertEqual(bdUrl,'https://www.baidu.com/',msg=u'当前页面url不正确')
sourceCode = self.driver.page_source
print(sourceCode)
def testGetwindowHandle(self):
'''
获取当前页面的句柄,切换窗口
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
self.driver.maximize_window()
current_handle = self.driver.current_window_handle
print(current_handle)
self.driver.find_element_by_id('kw').send_keys('selenium')
self.driver.find_element_by_id('su').click()
time.sleep(3)
self.driver.find_element_by_partial_link_text(u'百度百科').click()
all_handles = self.driver.window_handles
print(all_handles)
print(self.driver.window_handles[-1])
for handle in all_handles:
if handle != current_handle:
self.driver.switch_to.window(handle)
self.driver.find_element_by_link_text(u'元素硒的英文名').click()
self.driver.switch_to.window(current_handle)
sendKeys = self.driver.find_element_by_id('kw')
sendKeys.clear()
sendKeys.send_keys('python')
def testGetElementInfo(self):
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
self.driver.maximize_window()
element = self.driver.find_element_by_xpath("//a[text()='新闻']")
print(u'我的tag_name是{},我的text是{},我的size是{}'.format(element.tag_name,element.text,element.size))
def testGetCssInfo(self):
'''
获取元素的css属性值
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
self.driver.maximize_window()
element = self.driver.find_element_by_id('kw')
print(element.value_of_css_property('height'))
print(element.value_of_css_property('width'))
print(element.value_of_css_property('font-family'))
def testInputClear(self):
'''
清空输入框数据
:return:
'''
baseBaiduUrl = 'https://www.baidu.com/'
self.driver.get(baseBaiduUrl)
self.driver.maximize_window()
element = self.driver.find_element_by_id('kw')
element.send_keys('python')
time.sleep(5)
element.clear()
def testElementIsDisplay(self):
'''
判断元素是否可见
:return:
'''
self.driver.get(r'file:///C:/Users/v-xug/Desktop/isdisplay.html')
self.driver.maximize_window()
div2 = self.driver.find_element_by_id('div2')
if div2.is_displayed():
print(u'div2 元素可见')
else:
print(u'div2 元素不可见')
button1 = self.driver.find_element_by_id('button1')
button1.click()
if div2.is_displayed():
print(u'div2 元素可见')
else:
print(u'div2 元素不可见')
div4 = self.driver.find_element_by_id('div4')
if div4.is_displayed():
print(u'div4 元素可见')
else:
print(u'div4 元素不可见')
button2 = self.driver.find_element_by_id('button2')
button2.click()
if div4.is_displayed():
print(u'div4 元素可见')
else:
print(u'div4 元素不可见')
def testElementIsEnable(self):
'''
判断元素是否可操作
:return:
'''
self.driver.get(r'file:///C:/Users/v-xug/Desktop/isenable.html')
self.driver.maximize_window()
input1 = self.driver.find_element_by_id('input1')
if input1.is_enabled():
print(u'input1 可操作')
else:
print(u'input1 不可操作')
input2 = self.driver.find_element_by_id('input2')
if input2.is_enabled():
print(u'input2 可操作')
else:
print(u'input2 不可操作')
input3 = self.driver.find_element_by_id('input3')
if input3.is_enabled():
print(u'input3 可操作')
else:
print(u'input3 不可操作')
def testGetAttribute(self):
'''
获取元素属性值
:return:
'''
self.driver.get('http://www.sogou.com')
self.driver.maximize_window()
query = self.driver.find_element_by_id('query')
print(query.get_attribute('name'))
query.send_keys('python')
print(query.get_attribute('value'))
def testDoubleClick(self):
'''
模拟鼠标双击事件
:return:
'''
from selenium.webdriver import ActionChains
import time
self.driver.get(r'file:///C:/Users/v-xug/Desktop/doubleclick.html')
self.driver.maximize_window()
time.sleep(3)
inputbox = self.driver.find_element_by_id('inputBox')
action = ActionChains(self.driver)
action.double_click(inputbox).perform()
time.sleep(3)
def testSelect(self):
'''
操作select下拉列表元素
:return:
'''
import time
self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
self.driver.maximize_window()
select = self.driver.find_element_by_name('fruit')
elements = select.find_elements_by_xpath("//option")
for element in elements:
print(element.text)
print(element.get_attribute('value'))
element.click()
time.sleep(1)
def testSelectOption(self):
import time
from selenium.webdriver.support.ui import Select
self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
self.driver.maximize_window()
select_element = Select(self.driver.find_element_by_xpath('//select'))
print(select_element.first_selected_option.text)
all_options = select_element.options
print(len(all_options))
if all_options[1].is_enabled() and not all_options[1].is_selected():
select_element.select_by_index(1)
print(select_element.all_selected_options[0].text)
time.sleep(2)
select_element.select_by_visible_text(u'猕猴桃')
self.assertEqual(select_element.all_selected_options[0].text, u'猕猴桃')
time.sleep(2)
select_element.select_by_value('shanzha')
print(select_element.all_selected_options[0].text)
self.assertEqual(select_element.all_selected_options[0].text, u'山楂')
def testAssertOptions(self):
from selenium.webdriver.support.ui import Select
self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
self.driver.maximize_window()
select_element = Select(self.driver.find_element_by_xpath('//select'))
actual_options = select_element.options
print(actual_options)
expect_optionslist = [u'桃子',u'西瓜',u'橘子',u'猕猴桃',u'山楂',u'荔枝']
actual_optionslist = [actual_options for actual_options in map(lambda option:option.text, actual_options)]
print(actual_optionslist)
self.assertListEqual(expect_optionslist, actual_optionslist)
def testMultipleOptions(self):
from selenium.webdriver.support.ui import Select
import time
self.driver.get(r'file:///C:/Users/v-xug/Desktop/multipleOptions.html')
self.driver.maximize_window()
select_element = Select(self.driver.find_element_by_xpath('//select'))
print(select_element.all_selected_options)
select_element.select_by_index(0)
print(select_element)
print(select_element.select_by_index(0))
select_element.select_by_visible_text(u'山楂')
print(select_element.select_by_visible_text(u'山楂'))
select_element.select_by_value('nihoutao')
print(select_element.select_by_value('nihoutao'))
for option in select_element.all_selected_options:
print(option.text)
select_element.select_by_index(1)
print(select_element.select_by_index(1))
select_element.select_by_value('juzi')
print(select_element.select_by_value('juzi'))
select_element.select_by_visible_text(u'荔枝')
print(select_element.select_by_visible_text(u'荔枝'))
print(select_element.deselect_all())
select_element.deselect_by_index(0)
print(select_element.deselect_by_index(0))
select_element.deselect_by_value('nihoutao')
print(select_element.deselect_by_value('nihoutao'))
select_element.deselect_by_visible_text(u'山楂')
print(select_element.deselect_by_visible_text(u'山楂'))
def testInputSelect(self):
from selenium.webdriver.common.keys import Keys
import time
self.driver.get(r'file:///C:/Users/v-xug/Desktop/inputselect.html')
self.driver.maximize_window()
inputselect = self.driver.find_element_by_id('select')
inputselect.clear()
time.sleep(1)
inputselect.send_keys('c', Keys.ARROW_DOWN)
time.sleep(1)
inputselect.send_keys(Keys.ARROW_DOWN)
time.sleep(1)
inputselect.send_keys(Keys.ENTER)
time.sleep(3)
def testRadio(self):
import time
self.driver.get(r'file:///C:/Users/v-xug/Desktop/radio.html')
self.driver.maximize_window()
berry = self.driver.find_element_by_xpath("//input[@value='berry']")
berry.click()
time.sleep(2)
self.assertTrue(berry.is_selected())
if berry.is_selected():
watermelon = self.driver.find_element_by_xpath("//input[@value='watermelon']")
watermelon.click()
self.assertFalse(berry.is_selected())
options = self.driver.find_elements_by_xpath("//input[@name='fruit']")
for option in options:
if option.get_attribute('value')=='orange':
if not option.is_selected():
option.click()
def testCheckBox(self):
self.driver.get(r'file:///C:/Users/v-xug/Desktop/checkbox.html')
self.driver.maximize_window()
berry = self.driver.find_element_by_xpath("//input[@value='berry']")
berry.click()
self.assertTrue(berry.is_selected())
if berry.is_selected():
berry.click()
options = self.driver.find_elements_by_xpath("//input[@name='fruit']")
for option in options:
if not option.is_selected():
option.click()
def testAssertIn(self):
import time
self.driver.get('http://www.baidu.com')
self.driver.maximize_window()
self.driver.find_element_by_id('kw').send_keys(u'linux超')
self.driver.find_element_by_id('su').click()
time.sleep(4)
self.assertIn(u'linux超', self.driver.page_source, msg=u'页面源码中不存在该关键字')
def testScreenShot(self):
'''
页面截图操作
:return:
'''
self.driver.get('http://www.baidu.com')
self.driver.maximize_window()
try:
self.driver.get_screenshot_as_file('baidu.png')
except IOError as e:
print(e)
def testDragDrop(self):
'''
模拟鼠标拖拽
:return:
'''
import time
from selenium.webdriver import ActionChains
self.driver.get(r'http://jqueryui.com/resources/demos/draggable/scroll.html')
self.driver.maximize_window()
element1 = self.driver.find_element_by_id('draggable')
element2 = self.driver.find_element_by_id('draggable2')
element3 = self.driver.find_element_by_id('draggable3')
action = ActionChains(self.driver)
action.drag_and_drop(element1, element2).perform()
for i in range(2):
action.drag_and_drop_by_offset(element3,10,10).perform()
time.sleep(2)
action.release()
def testSingleKey(self):
import time
from selenium.webdriver.common.keys import Keys
self.driver.get('http://www.sogou.com')
self.driver.maximize_window()
query = self.driver.find_element_by_id('query')
query.send_keys(Keys.F12)
time.sleep(2)
query.send_keys('selenium')
query.send_keys(Keys.ENTER)
time.sleep(2)
def testSimulationCombinationKeys(self):
'''
模拟组合按键
:return:
'''
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time
url = 'http://www.baidu.com'
self.driver.get(url)
self.driver.maximize_window()
input = self.driver.find_element_by_id('kw')
input.send_keys('python')
time.sleep(2)
ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
time.sleep(2)
ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
time.sleep(2)
self.driver.refresh()
time.sleep(2)
ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
time.sleep(1)
self.driver.find_element_by_id('su').click()
def testSimulationLeftClickMouseOfprocess(self):
'''
模拟鼠标左键按下与释放
鼠标左键点击百度首页的新闻(新闻左键点击不放会变为蓝色)
:return:
'''
from selenium.webdriver import ActionChains
import time
url = 'http://www.baidu.com'
self.driver.get(url)
self.driver.maximize_window()
element = self.driver.find_element_by_link_text(u'新闻')
ActionChains(self.driver).click_and_hold(element).perform()
time.sleep(2)
ActionChains(self.driver).release(element).perform()
time.sleep(2)
def testMouseOnElement(self):
'''
鼠标悬停在某个元素上
:return:
'''
from selenium.webdriver import ActionChains
import time
url = 'http://www.baidu.com'
self.driver.get(url)
self.driver.maximize_window()
newInfo = self.driver.find_element_by_link_text(u'新闻')
hao123 = self.driver.find_element_by_link_text('hao123')
action = ActionChains(self.driver)
action.move_to_element(newInfo).perform()
time.sleep(2)
action.move_to_element(hao123).perform()
def isElementpresent(self,*element):
from selenium.common.exceptions import NoSuchElementException
try:
self.driver.find_element(*element)
except NoSuchElementException as e:
print(e)
return False
else:
return True
def testIselementPresent(self):
url = 'http://www.sogou.com'
element = ('id', 'query')
self.driver.get(url)
ret = self.isElementpresent(*element)
if ret is True:
print(u'元素存在')
else:
print(u'元素不存在')
def testTitleWindow(self):
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time
url = 'file:///C:/Users/v-xug/Desktop/titleWindow.html'
self.driver.get(url)
sogou = self.driver.find_element_by_link_text(u'sogou 搜索')
sogou.click()
time.sleep(3)
all_handles = self.driver.window_handles
print(self.driver.current_window_handle)
print(len(all_handles))
if len(all_handles) > 0:
try:
for windowhandl in all_handles:
self.driver.switch_to.window(windowhandl)
print(u'窗口',self.driver.title)
if self.driver.title == u'搜狗搜索引擎 - 上网从搜狗开始':
inputBox = self.driver.find_element_by_id('query')
inputBox.send_keys('python')
time.sleep(2)
except NoSuchElementException as e:
print(e)
except TimeoutException as e:
print(e)
self.driver.switch_to.window(all_handles[0])
print(self.driver.title)
self.assertEqual(self.driver.title, u'使用title属性识别和操作新弹出的浏览器窗口')
def testHandleFrame(self):
'''
操作frame中的页面元素
:return:
'''
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
self.driver.get(r'file:///C:/Users/v-xug/Desktop/frameset.html')
self.driver.switch_to.frame(0)
left_ele_text = self.driver.find_element_by_xpath('//p')
leftText = left_ele_text.text
print(leftText)
self.assertEqual(leftText, u'这是左侧frame页面上的文字')
button = self.driver.find_element_by_tag_name('input')
button.click()
try:
alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present())
print(alert.text)
alert.accept()
except TimeoutException as e:
print(e)
self.driver.switch_to.default_content()
self.driver.switch_to.frame(1)
middle_ele = self.driver.find_element_by_xpath('//p')
print(middle_ele.text)
self.assertEqual(middle_ele.text, u'这是中间frame页面上的文字')
middle_input = self.driver.find_element_by_tag_name('input')
middle_input.send_keys('python')
self.driver.switch_to.default_content()
def testHandleCookie(self):
'''
操作页面的cookie信息
:return:
'''
self.driver.get('https://www.sogou.com/')
cookies = self.driver.get_cookies()
print(cookies)
for cookie in cookies:
print('%s->%s->%s->%s->%s'%(cookie['domain'],cookie['name'], cookie['value'],cookie['expiry'],cookie['path']))
ck = self.driver.get_cookie('SUV')
print('%s->%s->%s->%s->%s' % (ck['domain'], ck['name'], ck['value'], ck['expiry'], ck['path']))
print(self.driver.delete_cookie('ABTEST'))
self.driver.delete_all_cookies()
print(self.driver.get_cookies())
self.driver.add_cookie({'name':'gloryroadTrain','value':'1479697159269020'})
print(self.driver.get_cookie('gloryroadTrain'))
def testSetLoadPageTimeOut(self):
'''
指定页面加载时间
:return:
'''
import time
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
self.driver.set_page_load_timeout(10)
try:
starttime = time.time()
self.driver.get('https://mail.126.com')
except TimeoutException:
print(u'页面加载超时')
self.driver.execute_script('window.stop()')
end = time.time() - starttime
print(end)
self.driver.switch_to.frame(self.driver.find_element_by_xpath("//div[@id='loginDiv']/iframe"))
time.sleep(2)
username = self.driver.find_element_by_xpath("//input[@name='email']")
username.send_keys('281754043')
time.sleep(2)
password = self.driver.find_element_by_xpath("//input[@name='password']")
password.send_keys('xiaochao11520')
password.send_keys(Keys.ENTER)
def test_AjaxBykeys(self):
'''
在ajax方式产生的悬浮框中,单击选择包含某个关键字的选项
:return:
'''
from selenium.webdriver.common.keys import Keys
import time
self.driver.get('https://www.sogou.com')
query = self.driver.find_element_by_xpath("//input[@id='query']")
query.send_keys('python')
time.sleep(2)
for i in range(3):
query.send_keys(Keys.DOWN)
time.sleep(1)
query.send_keys(Keys.ENTER)
def test_killWindowProcess(self):
import os
self.driver.get('http://www.baidu.com')
recode = os.system('taskkill /iM firefox.exe /F')
if recode == 0:
print(u'结束Chrome进程成功')
else:
print(u'结束浏览器进程失败')
def test_uploadfile(self):
import time
self.driver.get('file:///C:/Users/v-xug/Desktop/fileupload.html')
upload = self.driver.find_element_by_id('file')
upload.send_keys(r'D:\mygithub\WebdriverAPI\test.py')
time.sleep(5)
submit = self.driver.find_element_by_id('filesubmit')
submit.click()
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
三.实例二
1.操作富文本框实例:通过js发送正文
from selenium import webdriver
import unittest
import time
''' 常用webdriverApi详解(基础部分)'''
class MyTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
def test_SohuSendMail(self):
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchWindowException
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.action_chains import ActionChains
url = 'http://mail.sohu.com'
self.driver.get(url)
time.sleep(2)
try:
username = self.driver.find_element_by_xpath("//input[@placeholder='请输入您的邮箱']")
username.send_keys('13691579846@sohu.com')
password = self.driver.find_element_by_xpath("//input[@placeholder='请输入您的密码']")
password.send_keys('xiaochao11520')
commitBtn = self.driver.find_element_by_xpath("//input[@type='submit']")
commitBtn.click()
'''判断某个元素中是否可见并且是enable的,代表可点击'''
wait = WebDriverWait(self.driver, 5)
wait.until(EC.element_to_be_clickable((By.XPATH, "//li[text()='写邮件']"))).click()
time.sleep(5)
'''
WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//div[@arr='mail.to_render']"))).click()
ActionChains(self.driver).click(self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")).send_keys('281754043@qq.com').perform()
'''
'''
WebDriverWait(self.driver,15,0.5).until(EC.visibility_of_element_located((By.XPATH,"//div[@arr='mail.to_render']"))).click()
ActionChains(self.driver).click(self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")).send_keys(u"413950612@qq.com").perform()
'''
name = self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")
action = ActionChains(self.driver)
action.move_to_element(name)
action.click(name)
action.send_keys(u"413950612@qq.com")
action.perform()
'''
name = self.driver.find_element_by_xpath("//div[@arr='mail.to_render']").click()
actions = ActionChains(self.driver).move_to_element(name)
actions.send_keys(u"413950612@qq.com") # 在输入文本框
actions.perform() # 这个一定要的perform()方法(只有使用了perform方法才会输入进去)
'''
self.driver.find_element_by_xpath("//body/div[@id='mailContent']/div[1]/div[1]/div[1]/div[4]/input[1]").clear()
subject = self.driver.find_element_by_xpath("//body/div[@id='mailContent']/div[1]/div[1]/div[1]/div[4]/input[1]")
subject.send_keys(u'测试邮件')
time.sleep(2)
ifram = self.driver.find_element_by_xpath("//iframe[contains(@id,'ueditor_0')]")
self.driver.switch_to.frame(ifram)
self.driver.execute_script("document.getElementsByTagName('body')[0].innerHTML='<b>邮件正文内容<b>'")
time.sleep(2)
self.driver.switch_to.default_content()
time.sleep(2)
send = self.driver.find_element_by_xpath("//span[text()='发送']")
send.click()
time.sleep(2)
'''判断某个元素是否被添加到了dom里并且可见,可见代表元素可显示且宽和高都大于0'''
'''判断元素是否可见,如果可见就返回这个元素'''
'''判断某个元素是否被加到了dom树里,并不代表该元素一定可见,如果定位到就返回WebElement'''
result = self.driver.find_element_by_xpath("//span[contains(text(),'发送成功')]").text
print(result)
self.assertEqual(u'发送成功', result)
except TimeoutException as e:
raise
except NoSuchWindowException as e:
raise e
except Exception as e:
raise e
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|