├── .gitignore ├── 1.py ├── 10.py ├── 11.py ├── 12.py ├── 13.py ├── 14.py ├── 15.py ├── 16.py ├── 17.py ├── 18.py ├── 2.py ├── 3.py ├── 4.py ├── 5.py ├── 6.py ├── 7.py ├── 8.py ├── 9.py ├── drag_and_drop.js ├── load_jquery.js ├── readme.md ├── requirement └── sm.py /.gitignore: -------------------------------------------------------------------------------- 1 | *pyc 2 | *swp 3 | *sw0 4 | wd/* 5 | -------------------------------------------------------------------------------- /1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | from selenium.webdriver.common.keys import Keys 5 | import time 6 | 7 | # 目前支持的driver有Firefox, Chrome, IE和Remote等 8 | driver = webdriver.Firefox(executable_path="./geckodriver") 9 | # 直到页面被加载完(onload被触发)才将控制权返回脚本 10 | driver.get('https://www.baidu.com') 11 | assert u'百度一下,你就知道' in driver.title 12 | print u"当前URL:", driver.current_url 13 | 14 | elem = driver.find_element_by_name('wd') 15 | # 清空预填充内容 16 | elem.clear() 17 | # Keys对象表示键盘按键,如F1、ALT等 18 | elem.send_keys(u'48.HTTP基本认证与摘要认证', Keys.RETURN) 19 | 20 | try: 21 | assert u'Mars Loo的博客' in driver.page_source 22 | except Exception as e: 23 | print e 24 | finally: 25 | time.sleep(2) 26 | # quit方法关闭整个浏览器 27 | driver.quit() 28 | -------------------------------------------------------------------------------- /10.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | import time 5 | 6 | 7 | ff = webdriver.Firefox() 8 | ff.get('http://mars:loo@localhost:5000/') 9 | time.sleep(2) 10 | ff.quit() 11 | -------------------------------------------------------------------------------- /11.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | from sm import sleep 5 | 6 | 7 | @auto_close 8 | def func(): 9 | a = ff.find_element_by_tag_name('a') 10 | a.click() 11 | print "Go back" 12 | sleep(2) 13 | ff.back() 14 | print "Go forward" 15 | sleep(2) 16 | ff.forward() 17 | -------------------------------------------------------------------------------- /12.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | 5 | 6 | @auto_close 7 | def func(): 8 | ff.add_cookie({'name': 'username', 'value': 'marsloo'}) 9 | ff.get('http://localhost:5000/') 10 | # 获取当前域的cookies 11 | print ff.get_cookies() 12 | -------------------------------------------------------------------------------- /13.py: -------------------------------------------------------------------------------- 1 | from sm import ff, auto_close 2 | from selenium.common.exceptions import NoSuchElementException 3 | 4 | 5 | @auto_close 6 | def func(): 7 | ff.implicitly_wait(3) 8 | try: 9 | a = ff.find_element_by_partial_link_text('g') 10 | a.click() 11 | except NoSuchElementException: 12 | print "Page load fail or no such element" 13 | -------------------------------------------------------------------------------- /14.py: -------------------------------------------------------------------------------- 1 | from sm import ff, auto_close 2 | from selenium.webdriver.common.by import By 3 | from selenium.webdriver.support.ui import WebDriverWait 4 | from selenium.webdriver.support import expected_conditions as EC 5 | from selenium.common.exceptions import TimeoutException 6 | 7 | 8 | @auto_close 9 | def func(): 10 | try: 11 | a = WebDriverWait(ff, 3).until( 12 | EC.presence_of_element_located((By.TAG_NAME, "a"))) 13 | a.click() 14 | except TimeoutException: 15 | print "No such element" 16 | -------------------------------------------------------------------------------- /15.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | from selenium.webdriver.common.keys import Keys 5 | import time 6 | 7 | driver = webdriver.Chrome(executable_path="./chromedriver") 8 | driver.get('https://www.baidu.com') 9 | assert u'百度一下,你就知道' in driver.title 10 | print u"当前URL:", driver.current_url 11 | 12 | elem = driver.find_element_by_name('wd') 13 | elem.clear() 14 | elem.send_keys(u'36.在Ubuntu上打造方便好用的Python开发环境', Keys.RETURN) 15 | 16 | try: 17 | assert u'Mars Loo的博客' in driver.page_source 18 | except Exception as e: 19 | print e 20 | finally: 21 | time.sleep(2) 22 | driver.close() 23 | -------------------------------------------------------------------------------- /16.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | 3 | from selenium import webdriver 4 | import time 5 | 6 | ff = webdriver.Firefox() 7 | ff.get('http://selenium-python.readthedocs.io/faq.html') 8 | 9 | # 滚动至页面底部 10 | ff.execute_script("window.scrollTo(0, document.body.scrollHeight);") 11 | time.sleep(5) 12 | # 保存屏幕截图 13 | ff.save_screenshot('scroll.jpg') 14 | ff.close() 15 | -------------------------------------------------------------------------------- /17.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | from selenium.webdriver.chrome import service 5 | import time 6 | 7 | webdriver_service = service.Service('./operadriver') 8 | webdriver_service.start() 9 | driver = webdriver.Remote(webdriver_service.service_url, 10 | webdriver.DesiredCapabilities.OPERA) 11 | 12 | driver.get('https://www.baidu.com') 13 | assert u'百度一下,你就知道' in driver.title 14 | print u"当前URL:", driver.current_url 15 | time.sleep(4) 16 | 17 | # Opera的退出会报错: 18 | # Exception RuntimeError: RuntimeError('sys.meta_path must 19 | # be a list of import hooks',) in > ignored 21 | # 影响是会有operadriver进程残留,需要手动清除 22 | driver.close() 23 | -------------------------------------------------------------------------------- /18.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | import time 5 | import os 6 | 7 | os.environ["SELENIUM_SERVER_JAR"] = "selenium-server-standalone-2.53.1.jar" 8 | 9 | driver = webdriver.Safari(quiet=True) 10 | driver.get('https://www.baidu.com') 11 | assert u'百度一下,你就知道' in driver.title 12 | print u"当前URL:", driver.current_url 13 | time.sleep(4) 14 | driver.quit() 15 | -------------------------------------------------------------------------------- /2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from selenium import webdriver 4 | from selenium.webdriver.common.keys import Keys 5 | import time 6 | import unittest 7 | 8 | 9 | class BaiduSearch(unittest.TestCase): 10 | def setUp(self): 11 | self.driver = webdriver.Firefox(executable_path="./geckodriver") 12 | 13 | def test_search_in_baidu(self): 14 | driver = self.driver 15 | driver.get("http://www.baidu.com") 16 | self.assertIn(u'百度一下,你就知道', driver.title) 17 | elem = driver.find_element_by_name("wd") 18 | elem.send_keys(u"47.HTTP代理(转发代理&反向代理)与重定向") 19 | elem.send_keys(Keys.RETURN) 20 | time.sleep(2) 21 | self.assertIn(u"Mars Loo的博客", driver.page_source) 22 | 23 | def tearDown(self): 24 | time.sleep(2) 25 | self.driver.quit() 26 | 27 | if __name__ == "__main__": 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | import time 5 | 6 | 7 | @auto_close 8 | def func(): 9 | # 采用xpath获取第一个select元素 10 | element = ff.find_element_by_xpath("//select[@name='car']") 11 | # 获取所有选项,打印选项值并点击 12 | all_options = element.find_elements_by_tag_name("option") 13 | for option in all_options: 14 | time.sleep(1) 15 | print "Value is: %s" % option.get_attribute("value") 16 | option.click() 17 | -------------------------------------------------------------------------------- /4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | from selenium.webdriver.support.ui import Select 5 | import time 6 | 7 | 8 | @auto_close 9 | def func(): 10 | select = Select(ff.find_element_by_xpath("//select[@name='car']")) 11 | select.select_by_visible_text("infinity") 12 | time.sleep(2) 13 | select.select_by_value("bmw") 14 | time.sleep(2) 15 | select.select_by_index("0") 16 | time.sleep(2) 17 | # form = ff.find_element_by_name('survey') 18 | # form.submit() 19 | submit = ff.find_element_by_id('submit') 20 | submit.click() 21 | -------------------------------------------------------------------------------- /5.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | from selenium.webdriver.support.ui import Select 5 | 6 | 7 | @auto_close 8 | def func(): 9 | select = Select(ff.find_element_by_xpath("//select[@name='car']")) 10 | # 获取所有预选项 11 | print select.all_selected_options 12 | # 去选所有选项 13 | select.deselect_all() 14 | # 获取所有可选项 15 | print select.options 16 | -------------------------------------------------------------------------------- /6.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | jquery_url = "http://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.2.min.js" 5 | 6 | 7 | @auto_close 8 | def func(): 9 | ff.set_script_timeout(30) 10 | with open("load_jquery.js") as f: 11 | load_jquery_js = f.read() 12 | 13 | with open("drag_and_drop.js") as f: 14 | drag_and_drop_js = f.read() 15 | 16 | ff.execute_async_script(load_jquery_js, jquery_url) 17 | 18 | ff.execute_script(drag_and_drop_js + 19 | "$('#one').simulateDragDrop({ dropTarget: '#bin'});") 20 | -------------------------------------------------------------------------------- /7.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | 3 | from sm import ff, auto_close, sleep 4 | 5 | 6 | @auto_close 7 | def func(): 8 | a = ff.find_element_by_tag_name("a") 9 | # 保存原始窗口,window_handlers是目前wd打开的所有窗口的句柄列表 10 | prev = ff.window_handles[-1] 11 | # 点击超链接(targe="_blank")后,浏览器新窗口被激活 12 | a.click() 13 | # 保存新窗口 14 | new = ff.window_handles[-1] 15 | # 切换到原始窗口 16 | sleep(2) 17 | ff.switch_to_window(prev) 18 | print "Switch to prev success" 19 | sleep(2) 20 | # 切换到新窗口 21 | ff.switch_to_window(new) 22 | print "Switch to new success" 23 | -------------------------------------------------------------------------------- /8.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | from sm import sleep 5 | 6 | 7 | @auto_close 8 | def func(): 9 | # frames = ff.find_elements_by_tag_name('iframe') 10 | # ff.switch_to_frame(frames[0]) 11 | # element = ff.find_element_by_name('wd') 12 | # element.clear() 13 | # element.send_keys("This is a test") 14 | # # 切换到顶级frame,然后才可以切换到其他iframe 15 | # ff.switch_to_default_content() 16 | # ff.switch_to_frame(frames[-1]) 17 | # element = ff.find_element_by_name('email') 18 | # element.clear() 19 | # element.send_keys("Input to sohu") 20 | ff.switch_to_frame('frame1') 21 | element = ff.find_element_by_name('wd') 22 | element.clear() 23 | element.send_keys("This is a test") 24 | sleep(2) 25 | # 切换到顶级frame,然后才可以切换到其他iframe 26 | ff.switch_to_default_content() 27 | ff.switch_to_frame('frame2') 28 | element = ff.find_element_by_name('email') 29 | element.clear() 30 | element.send_keys("Input to sohu") 31 | -------------------------------------------------------------------------------- /9.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from sm import ff, auto_close 4 | 5 | 6 | @auto_close 7 | def func(): 8 | # 切换到当前弹出框并返回Alert对象 9 | alert = ff.switch_to_alert() 10 | # 获取弹出框的文本内容 11 | print "Alert text:", alert.text 12 | # 点击弹出框的确定按钮 13 | # alert.accept() 14 | # 点击弹出框的取消按钮 15 | # alert.dismiss() 16 | # 如果是prompt类型的弹出框,向其中输入内容 17 | alert.send_keys("This is my choice") 18 | # 然后点击prompt框的确定按钮 19 | alert.accept() 20 | -------------------------------------------------------------------------------- /drag_and_drop.js: -------------------------------------------------------------------------------- 1 | (function( $ ) { 2 | $.fn.simulateDragDrop = function(options) { 3 | return this.each(function() { 4 | new $.simulateDragDrop(this, options); 5 | }); 6 | }; 7 | $.simulateDragDrop = function(elem, options) { 8 | this.options = options; 9 | this.simulateEvent(elem, options); 10 | }; 11 | $.extend($.simulateDragDrop.prototype, { 12 | simulateEvent: function(elem, options) { 13 | /*Simulating drag start*/ 14 | var type = 'dragstart'; 15 | var event = this.createEvent(type); 16 | this.dispatchEvent(elem, type, event); 17 | 18 | /*Simulating drop*/ 19 | type = 'drop'; 20 | var dropEvent = this.createEvent(type, {}); 21 | dropEvent.dataTransfer = event.dataTransfer; 22 | this.dispatchEvent($(options.dropTarget)[0], type, dropEvent); 23 | 24 | /*Simulating drag end*/ 25 | type = 'dragend'; 26 | var dragEndEvent = this.createEvent(type, {}); 27 | dragEndEvent.dataTransfer = event.dataTransfer; 28 | this.dispatchEvent(elem, type, dragEndEvent); 29 | }, 30 | createEvent: function(type) { 31 | var event = document.createEvent("CustomEvent"); 32 | event.initCustomEvent(type, true, true, null); 33 | event.dataTransfer = { 34 | data: { 35 | }, 36 | setData: function(type, val){ 37 | this.data[type] = val; 38 | }, 39 | getData: function(type){ 40 | return this.data[type]; 41 | } 42 | }; 43 | return event; 44 | }, 45 | dispatchEvent: function(elem, type, event) { 46 | if(elem.dispatchEvent) { 47 | elem.dispatchEvent(event); 48 | }else if( elem.fireEvent ) { 49 | elem.fireEvent("on"+type, event); 50 | } 51 | } 52 | }); 53 | })(jQuery); 54 | -------------------------------------------------------------------------------- /load_jquery.js: -------------------------------------------------------------------------------- 1 | /** dynamically load jQuery */ 2 | (function(jqueryUrl, callback) { 3 | if (typeof jqueryUrl != 'string') { 4 | jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; 5 | } 6 | if (typeof jQuery == 'undefined') { 7 | var script = document.createElement('script'); 8 | var head = document.getElementsByTagName('head')[0]; 9 | var done = false; 10 | script.onload = script.onreadystatechange = (function() { 11 | if (!done && (!this.readyState || this.readyState == 'loaded' 12 | || this.readyState == 'complete')) { 13 | done = true; 14 | script.onload = script.onreadystatechange = null; 15 | head.removeChild(script); 16 | callback(); 17 | } 18 | }); 19 | script.src = jqueryUrl; 20 | head.appendChild(script); 21 | } 22 | else { 23 | callback(); 24 | } 25 | })(arguments[0], arguments[arguments.length - 1]); 26 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # 说明 2 | 3 | 请结合[CSDN博客](http://blog.csdn.net/a464057216/article/details/52717464)阅读代码。 4 | 5 | ## 1.py 6 | selenium入门示例。 7 | 8 | ## 2.py 9 | selenium与unittest结合做自动化测试。 10 | 11 | ## 3.py 12 | 操作``元素。 16 | 17 | ## 5.py 18 | 通过Select对象操作允许多选或有预选值的`