Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

2.3. python

2.3.1. 安装

		
sudo pip install -U selenium	
		
		

2.3.2. Demo

		
vim test.py

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.keys import Keys
from time

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert browser.title == "Yahoo!"
elem = browser.find_element_by_name("p") # Find the query box
elem.send_keys("selenium" +
Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API
try:
browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]")
except NoSuchElementException:
assert 0, "can't find seleniumhq"
browser.close()
		
		

2.3.3. python example

例 2.1. python testcase

			
from selenium import selenium
import unittest, time, re

class testcase(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "http://www.google.com/")
        self.selenium.start()

    def test_testcase(self):
        sel = self.selenium
        sel.open("/")
        sel.type("name=q", "netkiller")
        sel.click("name=btnG")
        self.assertEqual(u"Neo")

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
			
			

2.3.4. 浏览器

		
from selenium import webdriver

driver = webdriver.Safari()		# Safari 浏览器
driver = webdriver.Edge()      	# Edge浏览器
driver = webdriver.Chrome()    	# Chrome浏览器
driver = webdriver.Firefox()   	# Firefox浏览器
driver = webdriver.Ie()        	# Internet Explorer浏览器
driver = webdriver.Opera()     	# Opera浏览器
driver = webdriver.PhantomJS()  # PhantomJS		
		
		
浏览器窗口大小
			
driver.set_window_size(480, 800)			
			
			

窗口最大化

			
driver.maximize_window()			
			
			
浏览器后退,前进
			
# 后退 
driver.back()
# 前进 
driver.forward()
			
			
页面刷新
			
driver.refresh() # 刷新			
			
			
窗口切换

在不同的窗口和框架之间切换

			
# 切换窗口
driver.switch_to_window("windowName")
# 切换框架
driver.switch_to_frame("frameName")
# 回到默认窗口
driver.switch_to_default_content()
			
			

通过xpath定位iframe

			
iframe = driver.find_element_by_xpath('//*[@id="video-iframe"]')
driver.switch_to_frame(iframe)			
			
			
Cookie
			
get_cookies(): 获得所有cookie信息。
get_cookie(name): 返回字典的key为“name”的cookie信息。
add_cookie(cookie_dict) : 添加cookie。“cookie_dict”指字典对象,必须有name 和value 值。
delete_cookie(name,optionsString):删除cookie信息。“name”是要删除的cookie的名称,“optionsString”是该cookie的选项,目前支持的选项包括“路径”,“域”。
delete_all_cookies(): 删除所有cookie信息			
			
			
页面title
			
title = driver.title # 打印当前页面title
			
			
当前页面URL
			
url = driver.current_url # 打印当前页面URL				
			
			
获取 HTML 源码
			
html = browser.page_source			
			
			
关闭浏览器
			
close() 关闭单个窗口
quit() 关闭所有窗口			
			
			

2.3.5. 等待事件

隐式Waits

等待页面加载完毕

		
driver.implicitly_wait(10) # seconds		
		
			

implicitly_wait 只能延迟执行,无法判断页面是否被真正完全加载完毕。

显式Waits

等待页面加载直到发现某个元素为止。

		
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.netkiller.cn/")
try:
    element = WebDriverWait(driver,10).until(
        EC.presence_of_element_located((By.ID,"copyright"))
    )
finally:
    driver.quit()		
		
			
		
title_is
title_contains
presence_of_element_located
visibility_of_element_located
visibility_of
presence_of_all_elements_located
text_to_be_present_in_element
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
invisibility_of_element_located
element_to_be_clickable
staleness_of
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present		
		
			

等待,直到按钮可以点击为止

			
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver,10)
element = wait.until(EC.element_to_be_clickable((By.ID,'button')))			
			
			

2.3.6. 元素定位

CSS
		
driver.find_element_by_css_selector("div.group-left > ul > li:nth-child({}) > span".format(random.randint(2, 46))).click()		
		
			
XPath
				
ul = chrome.find_element_by_xpath('//*[@id="menu"]/ul')
list = ul.find_elements_by_xpath('li')
print(len(list))    # 计算有li数量
list[-1].text  		# 取最后一个li的文本内容
list[1].click()		# 点击第一个li
				
				
表格操作

指定行列取数据

			
#第二行第二列,tbody是对于表格的标签				
XPath表达式: //*[id = "table"]/tbody/tr[2]/td[2]   		
			
				

遍历表格,取出第四列

				
		tbody = self.browser.find_element_by_xpath('//table[@id="Order"]/tbody')
        rows = tbody.find_elements_by_tag_name('tr')
        print(len(rows))
        vinNoList = []
        for row in rows:
            vin = row.find_elements_by_tag_name('td')[3].text
            vinNoList.append(vin)
        
        vinNoList = vinNoList[1:]
        print(vinNoList)				
				
				
元素属性
			
方法				说明
is_selected()	元素是否被选中
is_enabled()	元素是否可用
is_displayed()	元素是否可见		
size: 			返回元素的尺寸。
text: 			获取元素的文本。
get_attribute(name): 获得属性值。
.clear() 		清空内容
driver.find_element_by_id('name').tag_name

driver.find_element_by_id('name').rect
## {'height': 36, 'width': 100, 'x': 737.8108520507812, 'y': 223.1344451904297}

driver.find_element_by_id('age').location 
## {'x': 738, 'y': 223}

元素父级元素对象

parent 属性用于获取元素的父级元素对象:
driver.find_element_by_id('logo').parent

driver.find_element_by_id('su').get_property('value') 
			
			
				
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

elem = wd.find_element_by_css_selector('#my-id')
html = wd.execute_script("return arguments[0].innerHTML;", elem)

html = elem.get_attribute('innerHTML')				
				
				

2.3.7. 键盘事件

以下为常用的键盘操作:

		
send_keys(Keys.BACK_SPACE) 删除键(BackSpace)
send_keys(Keys.SPACE) 空格键(Space)
send_keys(Keys.TAB) 制表键(Tab)
send_keys(Keys.ESCAPE) 回退键(Esc)
send_keys(Keys.ENTER) 回车键(Enter)
send_keys(Keys.CONTROL,'a') 全选(Ctrl+A)
send_keys(Keys.CONTROL,'c') 复制(Ctrl+C)
send_keys(Keys.CONTROL,'x') 剪切(Ctrl+X)
send_keys(Keys.CONTROL,'v') 粘贴(Ctrl+V)
send_keys(Keys.F1) 键盘 F1
……
send_keys(Keys.F12) 键盘 F12
		
		
		

2.3.8. 鼠标事件

在 WebDriver 中鼠标操作的方法封装在 ActionChains 类提供。

		
ActionChains 类提供了鼠标操作的常用方法:

perform(): 			执行所有 ActionChains 中存储的行为;
context_click(): 	右击;
double_click(): 	双击;
drag_and_drop(): 	拖动;
move_to_element(): 鼠标悬停。
		
		

鼠标悬停例子:

		
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get("https://www.baidu.cn")

# 定位到要悬停的元素
above = driver.find_element_by_link_text("设置")
# 对定位到的元素执行鼠标悬停操作
ActionChains(driver).move_to_element(above).perform()			
		
		

2.3.9. Screenshot

		
driver.get_screenshot_as_file("~/screenshot.png")		
		
		

2.3.10. 表单处理

下拉框
			
# 通过select选项的索引来定位选择对应选项(从0开始计数)
Select(s).select_by_index(5)
 
# 通过选项的value属性值来定位
Select(s).select_by_value('2')
 
# 通过选项的文本内容来定位
Select(s).select_by_visible_text('牡丹江')
 
# 返回第一个选中的optionElement对象
Select(s).first_selected_option
 
# 返回所有选中的optionElement对象
Select(s).all_selected_options
 
# 取消所有选中的option
Select(s).deselect_all()
 
# 通过option的index来取消对应的option
Select(s).deselect_by_index(1)
 
# 通过value属性,来取消对应option
Select(s).deselect_by_value('')
 
# 通过option的文本内容,取消对应的option
Select(s).deselect_by_visible_text('')			
			
			
			
# 定位下拉框,选择其中的选项
sel = driver.find_element_by_css_selector("select#nr")
sel.find_element_by_css_selector("option[value='20']").click()

# 直接定位到选项
driver.find_element_by_css_selector("select#nr>option:nth-child(2)").click()

s = driver.find_element_by_id("nr")
s.find_element_by_xpath("//option[@value='50']").click()

from selenium import webdriver
browser = webdriver.Firefox()
select_box = browser.find_element_by_name("countries") 
options = [x for x in select_box.find_elements_by_tag_name("option")]
for element in options:
    print(element.get_attribute("value"))
    
    

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as UI
import contextlib

with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get(url)
    select = UI.Select(driver.find_element_by_xpath('//select[@name="countries"]'))
    for option in select.options:
        print(option.text, option.get_attribute('value'))    
        
from selenium.webdriver.support.ui import Select 
dropdown_menu = Select(driver.find_element_by_name(<NAME>))
for option in dropdown_menu.options:
            print(option.text, option.get_attribute('value'))          			
			
			
文件上传
			
# 定位上传按钮,添加本地文件
driver.find_element_by_name("file").send_keys('/tmp/upload_file.txt')
			
			

2.3.11. 弹出对话框

		
alert = driver.switch_to_alert()
text:		返回 alert/confirm/prompt 中的文字信息。
accept():	接受现有警告框。
dismiss():	解散现有警告框。
send_keys(keysToSend):发送文本至警告框。
		
		
		

2.3.12. 调用JavaScript代码

		
# 通过javascript设置浏览器窗口的滚动条位置
js="window.scrollTo(100,450);"
driver.execute_script(js) 

span = 'document.getElementById("returnName1").innerHTML="设置 SPAN 文本" '
self.driver.execute_script(span)