pyrhon selenium基于显示等待封装的一些常用方法

import os
import time
from PIL import Image
from selenium import webdriver
from appium import webdriver as app
from selenium.common.exceptions import *
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from common.logger import Log
from common import readConfig

def open_browser(browser=‘chrome‘):
    """打开浏览器函数。"firefox"、"chrome"、"ie",‘phantomjs‘"""

    # 驱动路径
    driver_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    try:
        if browser == ‘firefox‘:
            executable_path = os.path.join(driver_path, ‘driver\\geckodriver.exe‘)
            # executable_path = os.path.join(driver_path, ‘driver/geckodriver‘)
            driver = webdriver.Firefox(executable_path=executable_path)
            return driver
        elif browser == ‘chrome‘:
            # 加启动配置,忽略 Chrome正在受到自动软件的控制 提示
            option = webdriver.ChromeOptions()
            option.add_argument(‘disable-infobars‘)
            # chrome启动静默模式;默认显示浏览器界面
            if readConfig.chrome_interface != ‘True‘:
                option.add_argument(‘headless‘)
            executable_path = os.path.join(driver_path, ‘driver\\chromedriver.exe‘)
            # executable_path = os.path.join(driver_path, ‘driver/chromedriver‘)
            driver = webdriver.Chrome(chrome_options=option, executable_path=executable_path)
            return driver
        elif browser == ‘ie‘:
            driver = webdriver.Ie()
            return driver
        elif browser == ‘js‘:
            driver = webdriver.PhantomJS()
            return driver
        else:
            Log().warning(‘额,暂不支持此浏览器诶。先试试firefox、chrome、ie、phantomJS浏览器吧。‘)
            return
    except Exception as msg:
        Log().error(‘浏览器出错了呀!%s‘ % msg)
        return

def open_app():
    try:
        desired_caps = {
            ‘platformName‘: readConfig.platform_name,

            ‘deviceName‘: readConfig.device_name,

            ‘platformVersion‘: readConfig.platform_version,

            ‘appPackage‘: readConfig.app_package,

            ‘appActivity‘: readConfig.app_activity,

            ‘noReset‘: True,

            # 隐藏手机默认键盘
            ‘unicodeKeyboard‘: True,

            ‘resetKeyboard‘: True
        }
        # 关联appium
        driver = app.Remote(‘http://127.0.0.1:4723/wd/hub‘, desired_caps)
        return driver
    except Exception as e:
        raise Exception(‘连接 Appium 出错:{}‘.format(e))

class Crazy:
    """基于原生的selenium框架做二次封装"""

    def __init__(self, driver):
        """启动浏览器参数化,默认启动chrome"""
        self.driver = driver

    def open(self, url, t=‘‘, timeout=5):
        """get url,最大化浏览器,判断title"""
        self.driver.get(url)
        self.driver.implicitly_wait(10)
        # 是否最大化浏览器
        if readConfig.maximize != ‘True‘:
            self.driver.maximize_window()
        try:
            WebDriverWait(self.driver, timeout, 1).until(EC.title_contains(t))
            Log().info(‘打开网页成功!‘)
        except TimeoutException:
            Log().error(‘打开%s title错误,超时‘ % url)
        except Exception as msg:
            Log().error(‘打开网页产生的其他错误:%s‘ % msg)

    def find_element(self, locator, timeout=5):
        """重写元素定位方法"""
        try:
            element = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator))
            y = element.is_displayed()
            if y:
                return element
        except:
            # Log().info(‘%s页面中未能找到元素%s‘ % (self, locator))
            return ""

    def find_elements(self, locator, timeout=5):
        """定位一组元素"""
        elements = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_all_elements_located(locator))
        return elements

    def click_coordinate(self, coordinate, timeout=10):
        """点击坐标"""
        self.driver.tap(coordinate, timeout)

    def clicks(self, locator, n):
        """点击一组元组中的一个"""
        element = self.find_elements(locator)[n]
        element.click()

    def click(self, locator, timeout=5):
        """点击操作"""
        element = self.find_element(locator, timeout=timeout)
        element.click()

    def send_keys(self, locator, text):
        """发送文本,清空后输入"""
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

    def is_text_in_element(self, locator, text, timeout=5):
        """判断文本在元素里,没定位到元素返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, timeout, 1).until(EC.text_to_be_present_in_element(locator, text))
            Log().info(‘is_text_in_element     成功‘)
            return result
        except TimeoutException:
            Log().error(‘%s元素没有定位到‘ % str(locator))
            return False

    def is_text_in_value(self, locator, value, timeout=5):
        """判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, timeout, 1).until(
                EC.text_to_be_present_in_element_value(locator, value))
        except TimeoutException:
            Log().error(‘元素没有定位到:%s‘ % str(locator))
            return False
        else:
            return result

    def is_title(self, title, timeout=5):
        """判断title完全等于"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.title_is(title))
        return result

    def is_title_contains(self, title, timeout=5):
        """判断title包含"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.title_contains(title))
        return result

    def is_selected(self, locator, timeout=5):
        """判断元素被选中,返回布尔值, 一般用在下拉框"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_to_be_selected(locator))
        return result

    def is_selected_be(self, locator, selected=True, timeout=5):
        """判断元素的状态,selected是期望的参数True/False,返回布尔值"""
        result = WebDriverWait(self.driver, timeout, 1).until(
            EC.element_located_selection_state_to_be(locator, selected))
        return result

    def is_alert_present(self, timeout=5):
        """判断页面是否有alert,有返回alert,没有返回False"""
        result = WebDriverWait(self.driver, timeout, 1).until((EC.alert_is_present()))
        text = EC.alert_is_present()(self.driver)
        if text:
            Log().info(‘alert弹框显示文本是:%s‘ % text.text)
        else:
            Log().warning(‘没有发现alert弹框。‘)
        return result

    def is_visibility(self, locator, timeout=5):
        """元素可见返回本身,不可见返回False"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.visibility_of_element_located(locator))
        return result

    def is_invisibility(self, locator, timeout=5):
        """元素可见返回本身,不可见返回True,没有找到元素也返回True"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.invisibility_of_element_located(locator))
        return result

    def is_clickAble(self, locator, timeout=5):
        """元素可以点击返回本身,不可点击返回False"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.element_to_be_clickable(locator))
        return result

    def is_locator(self, locator, timeout=10):
        """判断元素有没有被定位到(并不意味着可见),定位到返回element,没有定位到返回False"""
        result = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator))
        return result

    def move_to_element(self, locator):
        """鼠标悬停操作"""
        element = self.find_element(locator)
        ActionChains(self.driver).move_to_element(element).perform()

    def move(self, locator, locator1):
        """循环调用鼠标事件,死循环"""
        self.move_to_element(locator)
        time.sleep(2)
        element = self.find_element(locator1)
        self.move_to_element(locator1)
        try:
            if element.is_displayed:
                self.click(locator1)
            else:
                self.move(locator, locator1)
        except ElementNotVisibleException as e:
            Log().error(‘鼠标点击事件失败:%s‘ % e)

    def switch_frame(self, frame):
        """切换ifarm"""
        try:
            self.driver.switch_to_frame(self.find_element(frame))
            Log().info(‘切换iframe成功!‘)
        except:
            Log().warning(‘没有发现iframe元素%s‘ % frame)

    def back(self):
        """返回之前的网页"""
        self.driver.back()

    def forward(self):
        """前往下一个网页"""
        self.driver.forward()

    def close(self):
        """关闭当前网页"""
        self.driver.close()

    def quit(self):
        """关闭所有网页"""
        self.driver.quit()

    def get_title(self):
        """获取title"""
        return self.driver.title

    def get_texts(self, locator, n):
        """获取一组相同元素中的指定文本"""
        element = self.find_elements(locator)[n]
        if element:
            return element.text

    def get_text(self, locator):
        """获取文本"""
        element = self.find_element(locator)
        if element:
            return element.text

    def get_attribute(self, locator, name):
        """获取属性"""
        element = self.find_element(locator)
        if element:
            return element.get_attribute(name)

    def js_execute(self, js):
        """执行js"""
        return self.driver.execute_script(js)

    def js_focus_element(self, locator):
        """聚焦元素"""
        target = self.find_element(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();", target)

    def js_scroll_top(self):
        """滚动到顶部"""
        js = "window.scrollTo(0,document.body.scrollHeight)"
        self.driver.execute_script(js)

    def select_by_index(self, locator, index):
        """通过索引,index是第几个,从0开始, 下拉框"""
        element = self.find_element(locator)
        Select(element).select_by_index(index)

    def select_by_value(self, locator, value):
        """通过value属性"""
        element = self.find_element(locator)
        Select(element).select_by_value(value)

    def select_by_text(self, locator, text):
        """通过text属性"""
        element = self.find_element(locator)
        Select(element).select_by_visible_text(text)

    def save_screenshot(self, img_path):
        """获取电脑屏幕截屏"""
        self.driver.save_screenshot(img_path)

    def save_report_html(self):
        """可以在html报告中使用的截图"""
        self.driver.get_screenshot_as_base64()

    def save_element_img(self, locator, img_path):
        """获取元素截图"""
        self.driver.save_screenshot(img_path)
        element = self.find_element(locator)
        left = element.location[‘x‘]
        top = element.location[‘y‘]
        right = element.location[‘x‘] + element.size[‘width‘]
        bottom = element.location[‘y‘] + element.size[‘height‘]
        im = Image.open(img_path)
        im = im.crop((left, top, right, bottom))
        im.save(img_path)

    def get_cookies(self):
        """获取cookies"""
        return self.driver.get_cookies()

    def swipeDown(self, t=500, n=1):
        ‘‘‘向下滑动屏幕‘‘‘
        l = self.driver.get_window_size()
        x1 = l[‘width‘] * 0.5  # x坐标
        y1 = l[‘height‘] * 0.25  # 起始y坐标
        y2 = l[‘height‘] * 0.75  # 终点y坐标
        for i in range(n):
            self.driver.swipe(x1, y1, x1, y2, t)

    def swipeUp(self, t=500, n=1):
        ‘‘‘向上滑动屏幕‘‘‘
        l = self.driver.get_window_size()
        x1 = l[‘width‘] * 0.5  # x坐标
        y1 = l[‘height‘] * 0.65  # 起始y坐标
        y2 = l[‘height‘] * 0.25  # 终点y坐标
        for i in range(n):
            self.driver.swipe(x1, y1, x1, y2, t)

if __name__ == ‘__main__‘:
    driver = open_app()

原文地址:https://www.cnblogs.com/changqing8023/p/10153156.html

时间: 2024-11-10 14:14:03

pyrhon selenium基于显示等待封装的一些常用方法的相关文章

Selenium的显示等待

? 1 2 3 4 5 6 7 8 9 Function<WebDriver, Boolean> waitFn = new Function<WebDriver, Boolean>() { @Override public Boolean apply(WebDriver driver) {     Point newPos = page.getWDGAttrDetail().getLocation();     return newPos.getY() != prePos.getY

selenium 的显示等待和隐式等待的区别(记录加强版)

什么是显示等待和隐式等待? 显示等待就是有条件的等待隐式等待就是无条件的等待 隐式等待 当使用了隐式等待执行测试的时候,如果 WebDriver 没有在 DOM 中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常,换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是 0 from selenium import webdriver browser = webdriver.Chrome() browser.implicitly_wait(10

selenium中的三种等待方式(显示等待WebDriverWait()、隐式等待implicitly()、强制等待sleep())---基于python

我们在实际使用selenium或者appium时,等待下个等待定位的元素出现,特别是web端加载的过程,都需要用到等待,而等待方式的设置是保证脚本稳定有效运行的一个非常重要的手段,在selenium中(appium通用)常用的等待分为显示等待WebDriverWait().隐式等待implicitly_wait().强制等待sleep()三种,下面我们就分别介绍一下这三种等待的区别 在前面的博文中简单介绍了<强制等待和隐士等待的区别和理解>,本文再详细的结合案例进行理解. sleep(): 强

selenium中的显示等待,隐示等待,强制等待

我们在实际使用selenium或者appium时,等待下个等待定位的元素出现,特别是web端加载的过程,都需要用到等待,而等待方式的设置是保证脚本稳定有效运行的一个非常重要的手段,在selenium中(appium通用)常用的等待分为显示等待WebDriverWait().隐式等待implicitly_wait().强制等待sleep()三种,下面我们就分别介绍一下这三种等待的区别: 1.显式等待  WebDriverWait()      显式等待是你定义的一段代码,用于等待某个条件发生然后再

python selenium 中的显示等待WebDriverWait与条件判断expected_conditions

#coding=utf-8 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait base_url = "http://www.baidu.com"

selenium 的隐式等待和显示等待

等待 现在的网页越来越多采用了 Ajax 技术,这样程序便不能确定何时某个元素完全加载出来了.如果实际页面等待时间过长导致某个dom元素还没出来,但是你的代码直接使用了这个WebElement,那么就会抛出NullPointer的异常. 为了避免这种元素定位困难而且会提高产生 ElementNotVisibleException 的概率.所以 Selenium 提供了两种等待方式,一种是隐式等待,一种是显式等待. 隐式等待是等待特定的时间,显式等待是指定某一条件直到这个条件成立时继续执行. 1.

selenium等待方式之显示等待

有时候,页面元素并未及时加载出来导致后面的步骤无法执行 这里就需要在加载前添加等待时间,让目标元素有足够的时间加载出来 第一种方法:使用time.sleep() 这种方法过于强制,无论元素是否加载出来都要等指定的时间,导致脚本执行效率不高 第二种方法:隐式等待implicitly_wait() 这种方法比较全局性,意味着一旦启用,全局有效,所有步骤都需要等待所有页面元素加载完后才会继续执行后续脚本 第三种:显示等待WebDriverWait 通俗的说法,指定的某元素,等待加载出来后,再执行后续操

selenium相关导入By、Keys、WebDriverWait、ActionChains,显示等待与隐式等待

# -*- coding: utf-8 -*- """ @author: Dell Created on Tue Dec 24 12:33:56 2019 """ import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait#等待一个元素加载完成 from selenium.webdriver.support i

【Selenium】显示、隐式等待

显示等待 WebDriverWait 超时抛出TimeOutException,默认500毫秒 public class WaitToReturnElement { /* * 设置超时时间为5秒,返回指定xpath的WebElement * */ public static WebElement waitForByXpath(final WebDriver driver,final String xpath) { WebDriverWait wait = new WebDriverWait(dr