selenium 全天课整理
Posted xiaoxiao075
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selenium 全天课整理相关的知识,希望对你有一定的参考价值。
# encoding=utf-8 ‘‘‘ selenium 全天 二 ‘‘‘ #unittest例子 from selenium import webdriver import unittest,time from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains class VisitSogouBaiduByChrome(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path=‘f:\\chromedriver‘) self.url1= ‘https://www.baidu.com‘ self.url2 = ‘https://cn.bing.com‘ self.wwait=WebDriverWait(self.driver,10,0.4) def test_visit_baidu(self): self.driver.get(self.url1) print(‘当前网页为:‘, self.driver.current_url) self.wwait.until(lambda x:x.find_element_by_id(‘kw‘)).send_keys(‘我是谁‘) self.wwait.until(lambda x:x.find_element_by_id(‘su‘)).click() time.sleep(3) assert ‘成龙‘ in self.driver.page_source def test_visit_bing(self): self.driver.get(self.url2) print(‘当前网页为:‘, self.driver.current_url) self.wwait.until(lambda x:x.find_element_by_id(‘sb_form_q‘)).send_keys(‘猫鼠游戏‘) self.wwait.until(lambda x:x.find_element_by_id(‘sb_form_go‘)).click() time.sleep(3) assert ‘莱昂纳多‘ in self.driver.page_source def tearDown(self): self.driver.quit() if __name__==‘__main__‘: unittest.main() ‘‘‘ #执行的顺序: set_up #每个test的初始化 test_visitsogou #方法名称必须test开头 teardown set_up test_visitbaidu teardown #每个test的结束执行 ‘‘‘ ************************selenium API 基本操作 ************************* #页面后退、前进 driver.back() driver.forward() #页面刷新 driver.refresh() #强制刷新 不使用浏览器的缓存 #页面最大化 driver.maximize_window() #获取、设置窗口的坐标 左上角 0,0 往右+100 往下+200 driver.get_window_position() #设置窗口大小self.driver.get_window_size()、self.driver.set_window_size() driver.get_window_size() driver.set_window_size(width = 200, height = 400, windowHandle=‘current‘) driver.get_window_size(windowHandle=‘current‘) #窗口的名称 driver.title #获取到网页的源码,比http协议requests获取的源码全,js都可以执行后获取 driver.page_source #获取当前页面的url driver.current_url ********************************切换不同窗口 window_handles,driver.switch_to.window(now_handle)******************** import unittest import time import chardet from selenium import webdriver class VisitSogouByIE(unittest.TestCase): def setUp(self): # 启动IE浏览器 self.driver = webdriver.Chrome(executable_path="f:\\chromedriver") def test_operateWindowHandle(self): url = "https://www.baidu.com" self.driver.get(url) # 获取当前窗口句柄 now_handle = self.driver.current_window_handle # 百度搜索输入框中输入“w3cschool” self.driver.find_element_by_id("kw").send_keys("w3cschool") # 点击搜索按钮 self.driver.find_element_by_id("su").click() time.sleep(3) # 点击w3school在线教育链接 self.driver.find_element_by_xpath("//*[@id=‘2‘]/h3/a").click() time.sleep(5) print("++++", self.driver.window_handles) # 循环遍历所有新打开的窗口句柄,也就是说不包括主窗口 for handle in self.driver.window_handles: if handle != now_handle: # 切换窗口 self.driver.switch_to.window(handle) #切换窗口,也可以用下面的方法,但此种方法在selenium3.x以后官方已经不推荐使用了self.driver.switch_to_window(handle) # 点击html5链接 self.driver.find_element_by_link_text(‘HTML5‘).click() time.sleep(3) # 关闭当前的窗口 self.driver.close() # 不能用self.driver.quit() 否则整个浏览器会退出 time.sleep(3) # 返回主窗口 self.driver.switch_to.window(now_handle) time.sleep(2) self.driver.find_element_by_id("kw").clear() self.driver.find_element_by_id("kw").send_keys(u"光荣之路自动化测试培训") self.driver.find_element_by_id("su").click() time.sleep(5) def tearDown(self): # 退出浏览器 self.driver.quit() if __name__ == ‘__main__‘: unittest.main() **********************************另一种方式切换不同的窗口,window_handles,判断driver.title==""********************** import unittest import time from selenium import webdriver class VisitSogouByIE(unittest.TestCase): def setUp(self): # 启动chrome浏览器 self.driver = webdriver.Chrome(executable_path="f:\\chromedriver") def test_operateWindowHandle(self): url = "http://www.baidu.com" self.driver.get(url) # 获取当前窗口句柄 now_handle = self.driver.current_window_handle # 百度搜索输入框中输入“w3cschool” self.driver.find_element_by_id("kw").send_keys("w3cschool") # 点击搜索按钮 self.driver.find_element_by_id("su").click() time.sleep(3) # 点击w3school在线教育链接 self.driver.find_element_by_xpath("//*[@id=‘2‘]/h3/a").click() time.sleep(5) # 获取所有窗口句柄 all_handles = self.driver.window_handles # 循环遍历所有新打开的窗口句柄,也就是说不包括主窗口 for handle in all_handles: self.driver.switch_to.window(handle) if self.driver.title == "w3school 在线教程": # 点击HTML5链接 self.driver.find_element_by_link_text(‘HTML5‘).click() time.sleep(3) if self.driver.title == "w3cschool_百度搜索": time.sleep(2) self.driver.find_element_by_id("kw").clear() self.driver.find_element_by_id("kw").send_keys("我是谁") self.driver.find_element_by_id("su").click() time.sleep(5) def tearDown(self): # 退出IE浏览器 self.driver.quit() if __name__ == ‘__main__‘: unittest.main() ******************************组合按键keyDown(keyName)、keyUp(keyName)********************* import win32api import win32con import time VK_CODE = ‘enter‘:0x0D, ‘ctrl‘:0x11, ‘a‘:0x41, ‘v‘:0x56, ‘x‘:0x58, ‘t‘:0x54 #键盘键按下 def keyDown(keyName): win32api.keybd_event(VK_CODE[keyName], 0, 0, 0) #键盘键抬起 def keyUp(keyName): win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0) #(方法1)浏览器新开一个窗口 ctrl+t keyDown(‘ctrl‘) keyDown(‘t‘) keyUp(‘t‘) keyUp(‘ctrl‘) #(方法2) 浏览器新开一个窗口 open_window=‘window.open("http://www.baidu.com");‘ #新开一个空白窗口 open_window=‘window.open();‘ driver.execute_script(open_window) #获取元素的属性 news_element=driver.find_element_by_xpath("//*[text()=‘新闻‘]") print("元素的标签名:", newsElement.tag_name) print("元素的size:", newsElement.size) print("元素的文本:",newsElement.text) print("元素的链接:",newsElement.get_attribute("href")) print("元素的链接:", newsElement.get_property("href")) #判断元素是否可见 div2.is_displayed() #判断元素是否可操作,及通过 js 修改元素可操作 input1.is_enabled() driver.execute_script("document.getElementById(‘input2‘).disabled=false;") #获取页面文本框输入的内容 input_box=driver.find_element_by_id("kw") input_box.send_keys("w3cschool") print(input_box.get_attribute(‘value‘)) #获取页面元素的css的属性值 searchBox =driver.find_element_by_id("kw") # 使用页面元素对象的value_of_css_property()方法获取元素的CSS属性值 print (u"搜索输入框的高度是:", searchBox.value_of_css_property("height")) print (u"搜索输入框的宽度是:", searchBox.value_of_css_property("width")) font = searchBox.value_of_css_property("font-family") print (u"搜索输入框的字体是:", font) # 断言搜索输入框的字体是否是arial字体 assert font=="arial" #文本框清空 input_box.clear() #页面元素双击 from selenium.webdriver import ActionChains ActionChains(driver).double_click(inputBox).perform() #操作下拉框(普通方式) select = self.driver.find_element_by_name("fruit") all_options = select.find_elements_by_tag_name("option") #注意这个返回列表 for option in all_options: print (u"选项显示的文本:", option.text) print (u"选项值为:", option.get_attribute("value")) option.click() *************************Select方式操作下拉框************************* from selenium.webdriver.support.ui import Select select_element = Select(self.driver.find_element_by_xpath("//select")) # 打印默认选中项的文本 print (select_element.first_selected_option.text) #下拉框的所有选项 all_options = select_element.options #下拉框已选择的所有选项 select_element.all_selected_options #选择选项的三种方式 #通过序号 select_element.select_by_index(1) #通过选项的显示文本 select_element.select_by_visible_text("猕猴桃") #通过选项的value属性值 select_element.select_by_value("shanzha") #多选框的操作同上面下拉框 # 取消所有已选中项 select_element.deselect_all() select_element.select_by_index(1) select_element.select_by_visible_text("荔枝") select_element.select_by_value("juzi") # 通过选项文本取消已选中的文本为“荔枝”选项 select_element.deselect_by_visible_text("荔枝") # 通过序号取消已选中的序号为1的选项 select_element.deselect_by_index(1) # 通过选项的value属性值取消已选中的value=“juzi”的选项 select_element.deselect_by_value("juzi") #可以输入内容筛选的下拉框,选择提示的下拉内容,只支持IE from selenium.webdriver.common.keys import Keys driver.find_element_by_id("select").send_keys("c") #根据输入,下拉框提示筛选结果 driver.find_element_by_id("select").send_keys( Keys.ARROW_DOWN) #按向下键 选择结果 driver.find_element_by_id("select").send_keys( Keys.ARROW_DOWN) driver.find_element_by_id("select").send_keys( Keys.ENTER) #单选框的操作,直接通过xpath定位,然后click() berryRadio = driver.find_element_by_xpath("//input[@value=‘berry‘]") # 点击选择“草莓”选项 berryRadio.click() #复选框操作,直接通过xpath定位,然后click()选中,再次click()取消选择 berryCheckBox = self.driver.find_element_by_xpath("//input[@value=‘berry‘]") # 点击选择“草莓”选项 berryCheckBox.click() #断言,assert assert "首页" in driver.page_source, "页面源码中不存在该关键字!" #如果断言失败,提示的错误信息 *****************************浏览器内部,截屏get_screen_shot_as_file(filepath)*********************** result = driver.get_screenshot_as_file(r"e:\screenPicture.png") print (result) #成功返回True #截图 不只是浏览器 屏幕都可以截图,不能滚屏 from PIL import ImageGrab im=ImageGrab.grab() im.save("e:\\1.jpg","jpeg") #创建当前日期(年月日)的目录,然后截图(时分秒.png)存到目录 import os import os.path import time from selenium import webdriver urls=["http://www.baidu.com","http://www.sogou.com","http://cn.bing.com"] dir_name=time.strftime("%Y-%m-%d",time.localtime()) if not os.path.exists("e:\\"+dir_name): os.mkdir("e:\\"+dir_name) driver = webdriver.Ie(executable_path = "f:\\IEDriverServer") os.chdir("e:\\"+dir_name) for url in urls: driver.get(url) driver.get_screenshot_as_file(time.strftime("%H-%M-%S",time.localtime())+".png") ************************************页面元素拖拽***************************** import unittest import time import chardet from selenium import webdriver class VisitSogouByIE(unittest.TestCase): def setUp(self): #启动IE浏览器 #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver") #self.driver = webdriver.Ie(executable_path = "f:\\IEDriverServer") self.driver = webdriver.Chrome(executable_path = "f:\\chromedriver") def test_dragPageElement(self): url = "http://jqueryui.com/resources/demos/draggable/scroll.html" # 访问被测试网页 self.driver.get(url) # 获取页面上第一个能拖拽的页面元素 initialPosition = self.driver.find_element_by_id("draggable") # 获取页面上第二个能拖拽的页面元素 targetPosition = self.driver.find_element_by_id("draggable2") # 获取页面上第三个能拖拽的页面元素 dragElement = self.driver.find_element_by_id("draggable3") # 导入提供拖拽元素方法的模块ActionChains from selenium.webdriver import ActionChains import time """ 创建一个新的ActionChains,将webdriver实例对象driver作为参数值传入 然后通过WebDriver实例执行用户动作。 """ action_chains = ActionChains(self.driver) # 将页面上第一个能被拖拽的元素拖拽到第二个元素位置 action_chains.drag_and_drop(initialPosition, targetPosition).perform() # 将页面上第三个能拖拽的元素,向右下拖动10个像素,共拖动5次 for i in range(5): action_chains.drag_and_drop_by_offset(dragElement, 10, 10).perform() time.sleep(2) def tearDown(self): # 退出IE浏览器 self.driver.quit() if __name__ == ‘__main__‘: unittest.main() ********************************页面的键盘事件 send_keys(Keys.ENTER)************************* from selenium.webdriver.common.keys import Keys input_box.send_keys(Keys.F12) #IE浏览器打开调试模式 input_box.send_keys("selenium") #点击回车键 # 或者使用query.send_keys(Keys.RETURN) query.send_keys(Keys.ENTER) **********************键盘事件 的例子************************ import unittest from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys import win32clipboard as w import win32con import time import win32api # 读取剪切板 def getText(): w.OpenClipboard() d = w.GetClipboardData(win32con.CF_TEXT) w.CloseClipboard() return d # 设置剪切板内容 def setText(aString): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(win32con.CF_UNICODETEXT, aString) w.CloseClipboard() VK_CODE = ‘enter‘:0x0D, ‘ctrl‘:0x11, ‘a‘:0x41, ‘v‘:0x56, ‘x‘:0x58 #键盘键按下 def keyDown(keyName): win32api.keybd_event(VK_CODE[keyName], 0, 0, 0) #键盘键抬起 def keyUp(keyName): win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0) content = ‘我是谁‘ # 将content变量中的内容设置到剪切板中 setText(content) # 从剪切板中获取刚设置到剪切板中的内容 getContent = getText() print ("剪切板中的内容:",getContent.decode("gbk")) #注意需要转换字符串类型 # 将焦点切换到搜索输入框中 driver.find_element_by_id("kw").click() keyDown(‘ctrl‘) keyDown(‘v‘) # 释放Ctrl + v组合键 keyUp(‘v‘) keyUp(‘ctrl‘) # 点击“百度一下”搜索按钮 self.driver.find_element_by_id(‘su‘).click() ********************** ActionChains 执行ctrl+a ctrl+x ctrl+v**************************** import unittest import time import chardet from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys ActionChains(driver).key_down(Keys.CONTROL).send_keys(‘a‘).key_up(Keys.CONTROL).perform() #ctrl+a ActionChains(driver).key_down(Keys.CONTROL).send_keys(‘x‘).key_up(Keys.CONTROL).perform() #ctrl+x driver.get(url) driver.find_element_by_id("kw").click() # 模拟Ctrl + V组合键,将从剪切板中获取到的内容粘贴到搜索输入框中 ActionChains(driver).key_down(Keys.CONTROL).send_keys(‘v‘).key_up(Keys.CONTROL).perform() #ctrl+v # 点击“百度一下”搜索按钮 self.driver.find_element_by_id(‘su‘).click() **********************************利用win32的方式 实现上述例子************************* import unittest import time import chardet from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys # 导入模拟组合按键需要的包 import win32api import win32con import time VK_CODE = ‘enter‘:0x0D, ‘ctrl‘:0x11, ‘a‘:0x41, ‘v‘:0x56, ‘x‘:0x58, ‘t‘:0x54 #键盘键按下 def keyDown(keyName): win32api.keybd_event(VK_CODE[keyName], 0, 0, 0) #键盘键抬起 def keyUp(keyName): win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0) # 模拟Ctrl + a,选中输入框中所有的内容 keyDown(‘ctrl‘) keyDown(‘a‘) # 释放Ctrl + a组合键 keyUp(‘a‘) keyUp(‘ctrl‘) # 模拟Ctrl + x剪切所选中的内容 keyDown(‘ctrl‘) keyDown(‘x‘) keyUp(‘x‘) keyUp(‘ctrl‘) # 访问百度首页 self.driver.get("http://www.baidu.com") # 将焦点切换到搜索输入框中 self.driver.find_element_by_id("kw").click() # 模拟Ctrl + v组合键,进行粘贴 keyDown("ctrl") keyDown("v") keyUp(‘v‘) keyUp(‘ctrl‘) # 模拟回车键 keyDown(‘enter‘) keyUp(‘enter‘) ******************************************键盘所有按键的清单*********************************** VK_CODE = ‘backspace‘: 0x08, ‘tab‘: 0x09, ‘clear‘: 0x0C, ‘enter‘: 0x0D, ‘shift‘: 0x10, ‘ctrl‘: 0x11, ‘alt‘: 0x12, ‘pause‘: 0x13, ‘caps_lock‘: 0x14, ‘esc‘: 0x1B, ‘spacebar‘: 0x20, ‘page_up‘: 0x21, ‘page_down‘: 0x22, ‘end‘: 0x23, ‘home‘: 0x24, ‘left_arrow‘: 0x25, ‘up_arrow‘: 0x26, ‘right_arrow‘: 0x27, ‘down_arrow‘: 0x28, ‘select‘: 0x29, ‘print‘: 0x2A, ‘execute‘: 0x2B, ‘print_screen‘: 0x2C, ‘ins‘: 0x2D, ‘del‘: 0x2E, ‘help‘: 0x2F, ‘0‘: 0x30, ‘1‘: 0x31, ‘2‘: 0x32, ‘3‘: 0x33, ‘4‘: 0x34, ‘5‘: 0x35, ‘6‘: 0x36, ‘7‘: 0x37, ‘8‘: 0x38, ‘9‘: 0x39, ‘a‘: 0x41, ‘b‘: 0x42, ‘c‘: 0x43, ‘d‘: 0x44, ‘e‘: 0x45, ‘f‘: 0x46, ‘g‘: 0x47, ‘h‘: 0x48, ‘i‘: 0x49, ‘j‘: 0x4A, ‘k‘: 0x4B, ‘l‘: 0x4C, ‘m‘: 0x4D, ‘n‘: 0x4E, ‘o‘: 0x4F, ‘p‘: 0x50, ‘q‘: 0x51, ‘r‘: 0x52, ‘s‘: 0x53, ‘t‘: 0x54, ‘u‘: 0x55, ‘v‘: 0x56, ‘w‘: 0x57, ‘x‘: 0x58, ‘y‘: 0x59, ‘z‘: 0x5A, ‘numpad_0‘: 0x60, ‘numpad_1‘: 0x61, ‘numpad_2‘: 0x62, ‘numpad_3‘: 0x63, ‘numpad_4‘: 0x64, ‘numpad_5‘: 0x65, ‘numpad_6‘: 0x66, ‘numpad_7‘: 0x67, ‘numpad_8‘: 0x68, ‘numpad_9‘: 0x69, ‘multiply_key‘: 0x6A, ‘add_key‘: 0x6B, ‘separator_key‘: 0x6C, ‘subtract_key‘: 0x6D, ‘decimal_key‘: 0x6E, ‘divide_key‘: 0x6F, ‘F1‘: 0x70, ‘F2‘: 0x71, ‘F3‘: 0x72, ‘F4‘: 0x73, ‘F5‘: 0x74, ‘F6‘: 0x75, ‘F7‘: 0x76, ‘F8‘: 0x77, ‘F9‘: 0x78, ‘F10‘: 0x79, ‘F11‘: 0x7A, ‘F12‘: 0x7B, ‘F13‘: 0x7C, ‘F14‘: 0x7D, ‘F15‘: 0x7E, ‘F16‘: 0x7F, ‘F17‘: 0x80, ‘F18‘: 0x81, ‘F19‘: 0x82, ‘F20‘: 0x83, ‘F21‘: 0x84, ‘F22‘: 0x85, ‘F23‘: 0x86, ‘F24‘: 0x87, ‘num_lock‘: 0x90, ‘scroll_lock‘: 0x91, ‘left_shift‘: 0xA0, ‘right_shift ‘: 0xA1, ‘left_control‘: 0xA2, ‘right_control‘: 0xA3, ‘left_menu‘: 0xA4, ‘right_menu‘: 0xA5, ‘browser_back‘: 0xA6, ‘browser_forward‘: 0xA7, ‘browser_refresh‘: 0xA8, ‘browser_stop‘: 0xA9, ‘browser_search‘: 0xAA, ‘browser_favorites‘: 0xAB, ‘browser_start_and_home‘: 0xAC, ‘volume_mute‘: 0xAD, ‘volume_Down‘: 0xAE, ‘volume_up‘: 0xAF, ‘next_track‘: 0xB0, ‘previous_track‘: 0xB1, ‘stop_media‘: 0xB2, ‘play/pause_media‘: 0xB3, ‘start_mail‘: 0xB4, ‘select_media‘: 0xB5, ‘start_application_1‘: 0xB6, ‘start_application_2‘: 0xB7, ‘attn_key‘: 0xF6, ‘crsel_key‘: 0xF7, ‘exsel_key‘: 0xF8, ‘play_key‘: 0xFA, ‘zoom_key‘: 0xFB, ‘clear_key‘: 0xFE, ‘+‘: 0xBB, ‘,‘: 0xBC, ‘-‘: 0xBD, ‘.‘: 0xBE, ‘/‘: 0xBF, ‘`‘: 0xC0, ‘;‘: 0xBA, ‘[‘: 0xDB, ‘\\‘: 0xDC, ‘]‘: 0xDD, "‘": 0xDE, ‘`‘: 0xC0
以上是关于selenium 全天课整理的主要内容,如果未能解决你的问题,请参考以下文章