0


python 自动化测试之Selenium 模块

官网:https://www.selenium.dev/zh-cn/

一、安装
pip install selenium
二、声明浏览器
from selenium import webdriver
通过WebDriver, Selenium支持市场上所有主要浏览器, 如Chrome、Firefox、Internet Explorer、Edge和Safari. WebDriver尽量使用浏览器内置的自动化支持 来驱动浏览器.

brower= webdriver.Chrome()//谷歌
browser = webdriver.Firefox()//互火狐
browser = webdriver.Edge()//IE
browser = webdriver.PhantomJS()//谷歌
browser = webdriver.Safari()//世界之窗
三、配置项
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
//谷歌
chrome_options = webdriver.ChromeOptions() 或 chrome_options = Options()
brower=webdriver.Chrome(executable_path='chromedriver.exe,options=chrome_options)

# 添加启动参数
chrome_options.add_argument()
# 添加扩展应用 
chrome_options.add_extension()
chrome_options.add_encoded_extension()
# 添加实验性质的设置参数 
chrome_options.add_experimental_option()
# 设置调试器地址
chrome_options.debugger_address()
  • 常用配置参数
chrome_options.add_argument('--disable-infobars')  # 禁止策略化
chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
chrome_options.add_argument('--disable-gpu')  # 谷歌禁用GPU加速
chrome_options.add_argument('--incognito')  # 隐身模式(无痕模式)
chrome_options.add_argument('--disable-javascript')  # 禁用javascript
chrome_options.add_argument('--start-maximized')  # 最大化运行(全屏窗口),不设置,取元素会报错
chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面(无头模式). linux下如果系统不支持可视化不加这条会启动失败
chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  #调用原来的浏览器,不用再次登录即可重启
chrome_options.add_argument('lang=en_US') # 设置语言
chrome_options.add_argument('User-Agent=Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36')
针对chrome76版本及以上版本,需要去掉Chrome提示受到自动软件控制使用:
chrome_options.add_argument('disable-infobars') #去掉Chrome提示受到自动软件控制
针对chrome76版本及以上版本,需要使用
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  #以开发者模式启动调试chrome,可以去掉提示受到自动软件控制
chrome_options.add_experimental_option('useAutomationExtension', False)  #去掉提示以开发者模式调用
chrome_options.add_argument('disable-blink-features')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument('--kiosk-printing')  #这样就可以静默打印,直接使用默认打印机进行打印。如需是Chrome全屏+静默打印: 使用" --kiosk --kiosk-printing" :浏览器默认是全屏显示,而且Esc、F11和鼠标右键都无法使用,在软件编程时,使用JS调用浏览器打印功能时,会跳过打印预览,直接进行打印操作。
chrome_options.add_experimental_option('detach', True)  # 不自动关闭浏览器
chrome_options.add_extension('d:\crx\AdBlock_v2.17.crx') #添加crx插件

prefs = {
     'profile.default_content_setting_values' : {  
        'notifications' : 2 , # 禁用浏览器弹窗
        'images' : 2 #禁用图片加载
     },
     'profile.default_content_settings.geolocation':2,#禁用地理位置
     # 屏蔽'保存密码'提示框
     'credentials_enable_service': False,
     'profile.password_manager_enabled': False,
}
chrome_options.add_experimental_option("prefs", prefs)

# 通过设置user-agent,用来模拟移动设备
# 比如模拟 android QQ浏览器
options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"') 
# 模拟iPhone 6
options.add_argument('user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"')
  • 其他配置项
–user-data-dir=”[PATH]” # 指定用户文件夹User Data路径,可以把书签这样的用户数据保存在系统分区以外的分区
–disk-cache-dir=”[PATH]“ # 指定缓存Cache路径
–disk-cache-size= # 指定Cache大小,单位Byte
–first run # 重置到初始状态,第一次运行
–incognito # 隐身模式启动
–disable-javascript # 禁用Javascript
-omnibox-popup-count="num" # 将地址栏弹出的提示菜单数量改为num个
-user-agent="xxxxxxxx" # 修改HTTP请求头部的Agent字符串,可以通过about:version页面查看修改效果
-disable-plugins # 禁止加载所有插件,可以增加速度。可以通过about:plugins页面查看效果
-disable-javascript # 禁用JavaScript,如果觉得速度慢在加上这个
-disable-java # 禁用java
-start-maximized # 启动就最大化
-no-sandbox # 取消沙盒模式
-single-process # 单进程运行
-process-per-tab # 每个标签使用单独进程
-process-per-site # 每个站点使用单独进程
-in-process-plugins # 插件不启用单独进程
-disable-popup-blocking # 禁用弹出拦截
-disable-plugins # 禁用插件
-disable-images # 禁用图像
-incognito # 启动进入隐身模式
-enable-udd-profiles # 启用账户切换菜单
-proxy-pac-url # 使用pac代理 [via 1/2]
-lang=zh-CN # 设置语言为简体中文
-disk-cache-dir # 自定义缓存目录
-disk-cache-size # 自定义缓存最大值(单位byte)
-media-cache-size # 自定义多媒体缓存最大值(单位byte)
-bookmark-menu # 在工具 栏增加一个书签按钮
-enable-sync # 启用书签同步
-proxy-server #设置代理
-ignore-certificate-errors # 忽略证书错误
–single-process #单进程运行Google Chrome
--disable-extensions #禁用地理位置
四、常用方法
browser.get(r'https://www.baidu.com/')# 访问页面
brower.save_screenshot('screen.png')#保存网页截图
brower.get_screenshot_as_file('截图.png')# 截图预览
brower.close()# 关闭浏览器
browser.quit()# 关闭浏览器全部页面
browser.set_window_size(width=500, height=500, windowHandle="current")# 设置分辨率 500*500 
browser.refresh()  # 刷新页面
browser.maximize_window()# 设置浏览器全屏
browser.back()  # 后退
browser.forward() # 前进
browser.execute_script() #执行js
browser.add_cookie({'name':'才哥', 'value':'帅哥'}) #添加cookie
browser.delete_all_cookies() # 删除cookie
browser.get_cookies() # 获取cookie
browser.page_source.find('字符串') #源码中搜索字符串,可以是文本值也可以是属性值
browser.get_window_position() #获取浏览器在屏幕上的坐标
browser..set_window_position(x=100, y=200)#设置浏览器在屏幕的位置
五、常用属性
browser.title # 网页标题
browser.current_url # 当前网址
browser.name # 浏览器名称
browser.page_source # 网页源码
browser.current_window_handle #获取当前窗口的句柄。
browser.window_handles#返回当前浏览器的所有窗口的句柄。
  • switch_to属性
'''frame切换'''
brower.switch_to.frame() #根据元素id或 index切换
brower.switch_to.default_content() #切换到默认 frame
brower.switch_to.parent_frame() #切换到父级 frame

'''多窗口切换'''
brower.get("http://www.baidu.com")

windows = brower.window_handles # 所有窗口句柄

brower.switch_to.window(windows[-1]) # 切换到注册窗口

brower.switch_to.window(windows[0])# 切换回登录窗口

'''alert弹框'''
brower.switch_to.alert() #切换到当前页面上的警告框
brower.switch_to.alert.text#返回弹框文本信息
brower.switch_to.alert.accept()#接受弹框,确认
brower.switch_to.alert.dismiss()#取消弹框
brower.switch_to.alert.send_keys(keysToSend)#发送文本至弹框
brower.switch_to.alert.authenticate(username, password)#发送用户名和密码

```获取当前焦点元素```
brower.switch_to.active_element
六、操作元素
  • 定位元素from selenium.webdriver.common.by import By//find_element()和find_elements(),以下以find_element为例element = browser.find_element(By.CLASS_NAME, "last-item") # class定位element = browser.find_element(By.ID, "usernameId") # id定位element = browser.find_element(By.CSS_SELECTOR, ".password-section button") #css 定位element = browser.find_element(By.NAME, "password") # name 定位element = browser.find_element(By.TAG_NAME, "div") # 标签定位element = browser.find_element(By.LINK_TEXT, "新闻") #link定位element = browser.find_element(By.PARTIAL_LINK_TEXT, "闻") #link定位,模糊匹配element = browser.find_element(By.XPATH, "//*[@id="kw"]") #XPATH定位
  • 方法和属性element.get_attribute('src') # 获取属性element.send_keys('python') # 键盘操作element.clear()# 清空文本element.click() # 点击element.submit()# 回车确认element.text # 获取文本element.id # 获取idelement.location# 获取位置element.tag_name# 获取标签名element.size# 获取大小
  • 操作下拉框元素from selenium.webdriver.support.select import Select'''1、三种选择某一选项项的方法''' element.select_by_index() # 通过索引定位;注意:index索引是从“0”开始。element.select_by_value() # 通过value值定位,value标签的属性值。selement.elect_by_visible_text() # 通过文本值定位,即显示在下拉框的值。 '''2、三种返回options信息的方法''' element.options # 返回select元素所有的optionselement.all_selected_options # 返回select元素中所有已选中的选项element.first_selected_options # 返回select元素中选中的第一个选项 '''3、四种取消选中项的方法''' element.deselect_all # 取消全部的已选择项element.deselect_by_index # 取消已选中的索引项element.deselect_by_value # 取消已选中的value值element.deselect_by_visible_text # 取消已选中的文本值Select(element.select_by_index("2")# 根据索引选择Select(element.select_by_value("草儿")# 根据value值选择Select(element.select_by_visible_text("才哥")# 根据文本值选择
七、模拟鼠标操作
from selenium.webdriver.common.action_chains import ActionChains
actionChain = ActionChains(browser)
#ActionChains(browser):调用ActionChains()类,并将浏览器驱动browser作为参数传入
#actionChain.context_click(right_click):模拟鼠标双击,需要传入指定元素定位作为参数
#actionChain.perform():执行ActionChains()中储存的所有操作,可以看做是执行之前一系列的操作
#actionChain.click(on_element=None) ——单击鼠标左键
#actionChain.click_and_hold(on_element=None) ——点击鼠标左键,不松开
#actionChain.context_click(on_element=None) ——点击鼠标右键
#actionChain.double_click(on_element=None) ——双击鼠标左键
#actionChain.drag_and_drop(source, target) ——拖拽到某个元素然后松开
#actionChain.drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某个坐标然后松开
#actionChain.key_down(value, element=None) ——按下某个键盘上的键
#actionChain.key_up(value, element=None) ——松开某个键
#actionChain.move_by_offset(xoffset, yoffset) ——鼠标从当前位置移动到某个坐标
#actionChain.move_to_element(to_element) ——鼠标移动到某个元素
#actionChain.move_to_element_with_offset(to_element, xoffset, yoffset) ——移动到距某个元素(左上角坐标)多少距离的位置
#actionChain.release(on_element=None) ——在某个元素位置松开鼠标左键
#actionChain.send_keys(*keys_to_send) ——发送某个键到当前焦点的元素#
#actionChain.send_keys_to_element(element, *keys_to_send) ——发送某个键到指定元素
#actionChain.reset_actions()来清除坐标的累计,多次执行move_by_offset(xoffset, yoffset) ,移动的坐标会累加

element.click() #左键点击
actionChain.context_click(element).perform() #右键点击
actionChain.double_click(element).perform()#双击
actionChain.drag_and_drop(sourceEl, targetEl).perform()#拖拽
actionChain.move_to_element(element).perform()# 悬停操作
八、键盘操作
from selenium.webdriver.common.keys import Keys

#Keys.NULL
#Keys.CANCEL
#Keys.HELP
#Keys.BACKSPACE
#Keys.BACK_SPACE
#Keys.TAB
#Keys.CLEAR
#Keys.RETURN
#Keys.ENTER
#Keys.SHIFT
#Keys.LEFT_SHIFT
#Keys.CONTROL
#Keys.LEFT_CONTROL
#Keys.ALT
#Keys.LEFT_ALT
#Keys.PAUSE
#Keys.ESCAPE
#Keys.SPACE
#Keys.PAGE_UP
#Keys.PAGE_DOWN
#Keys.END
#Keys.HOME
#Keys.LEFT
#Keys.ARROW_LEFT
#Keys.UP
#Keys.ARROW_UP
#Keys.RIGHT
#Keys.ARROW_RIGHT
#Keys.DOWN
#Keys.ARROW_DOWN 
#Keys.INSERT
#Keys.DELETE
#Keys.SEMICOLON
#Keys.EQUALS
#Keys.NUMPAD0
#Keys.NUMPAD1
#Keys.NUMPAD2
#Keys.NUMPAD3 
#Keys.NUMPAD4
#Keys.NUMPAD5
#Keys.NUMPAD6
#Keys. NUMPAD7
#Keys.NUMPAD8
#Keys.NUMPAD9
#Keys.MULTIPLY
#Keys.ADD
#Keys.SEPARATOR
#Keys.SUBTRACT
#Keys.DECIMAL
#Keys.DIVIDE
#Keys.F1
#Keys.F2
#Keys.F3
#Keys.F4
#Keys.F5
#Keys.F6
#Keys.F7
#Keys.F8
#Keys.F9
#Keys.F10
#Keys.F11
#Keys.F12

    META = '\ue03d'
    COMMAND = '\ue03d'

element.send_keys(Keys.BACK_SPACE)#删除键(BackSpace)
element.send_keys(Keys.SPACE)#空格键(Space)
element.send_keys(Keys.TAB)#制表键(TAB)
element.send_keys(Keys.ESCAPE)#回退键(ESCAPE)
element.send_keys(Keys.ENTER)#回车键(ENTER)
element.send_keys(Keys.CONTROL,'a')#全选(Ctrl+A)
element.send_keys(Keys.CONTROL,'c')#复制(Ctrl+C)
element.send_keys(Keys.CONTROL,'x')#剪切(Ctrl+X)
element.send_keys(Keys.CONTROL,'v')#粘贴(Ctrl+V)
element.send_keys(Keys.F1)#键盘F1
.....
element.send_keys(Keys.F12)#键盘F12
八、延时等待
  • 强制等待import timetime.sleep(n)
  • 隐式等待browser.implicitly_wait(10)
  • 显式等待from selenium import webdriverfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECWebDriverWaitWebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)driver: 浏览器驱动timeout: 超时时间,等待的最长时间(同时要考虑隐性等待时间)poll_frequency: 每次检测的间隔时间,默认是0.5秒ignored_exceptions:超时后的异常信息,默认情况下抛出NoSuchElementException异常WebDriverWait.until(method,message='')method: 在等待期间,每隔一段时间调用这个传入的方法,直到返回值不是Falsemessage: 如果超时,抛出TimeoutException,将message传入异常until_not(method,message='')until_not 与until相反,until是当某元素出现或什么条件成立则继续执行,until_not是当某元素消失或什么条件不成立则继续执行,参数也相同。EC #EC.title_is(网页标题是否完全符合特定内容)#EC.title_contains(网页标题是否包含特定内容)#EC.presence_of_element_located(特定元素是否存在于页面DOM树中)#EC.presence_of_all_elements_located(定位的元素范围内,是否所有的元素都存在于DOM树中并且可见)#EC.visibility_of_element_located(特定元素是否存在于页面DOM树中并可见)#EC.invisibility_of_element_located(特定元素是否不可访问或不存在于DOM树)#EC.visibility_of(特定元素是否存在于页面DOM树中并可见)#EC.text_to_be_present_in_element(特定文本是否出现在特定元素中)#EC.text_to_be_present_in_element_value(特定文本是否在特定元素的value中)#EC.frame_to_be_available_and_switch_to_it(frame是否可被切换)#EC.staleness_of(特定元素是否不在附加于DOM树中)#EC.element_to_be_clickable(特定元素是否可点击)#EC.element_to_be_selected(特定元素是否被选中)#EC.element_located_to_be_selected( (特定元素是否存在于DOM树并被选中)#EC.element_selection_state_to_be(特定元素的选中状态是否与预期相同)#EC.element_located_selection_state_to_be(特定元素是否存在于DOM树,并且选中状态与预期是否相同)#EC.alert_is_present(弹出窗口是否存在)#EC.new_window_is_opened(用于判断新窗口是否打开,传入打开新窗口之前的window_handles)#EC.url_contains(检查当前url是否包含)#EC.url_matches(检查当前url是pattern预期的模式)#EC.url_to_be(检查当前urlurl的期望)#EC.url_changes(检查当前url是否相等) browser = webdriver.Chrome()browser.get('https://www.baidu.com')wait = WebDriverWait(browser, 10)# 设置等待时间10swait.until(EC.presence_of_element_located((By.ID, 'kw')))# 设置判断条件:等待id='kw'的元素加载完成
十、其他
  • 操作滚动条browser.execute_script("arguments[0].scrollIntoView();", ele) #滚动到目标元素browser.execute_script("document.documentElement.scrollTop=10000"); #上滚动browser.execute_script('window.scrollTo(x,y)') #滚动到指定的坐标。
  • 添加代理from selenium import webdriver设置代理服务器PROXY = "proxy_host:proxy:port"options = webdriver.ChromeOptions()desired_capabilities = options.to_capabilities()desired_capabilities['proxy'] = { "httpProxy": PROXY, "ftpProxy": PROXY, "sslProxy": PROXY, "noProxy": None, "proxyType": "MANUAL", "class": "org.openqa.selenium.Proxy", "autodetect": False}driver = webdriver.Chrome(desired_capabilities = desired_capabilities)本地代理,使用mitmproxychrome_options.add_argument('--proxy-server=127.0.0.1:9222') # 以9222端口启动谷歌浏览器
标签: python selenium chrome

本文转载自: https://blog.csdn.net/randy521520/article/details/131381740
版权归原作者 局外人LZ 所有, 如有侵权,请联系我们删除。

“python 自动化测试之Selenium 模块”的评论:

还没有评论