Example #1
0
 def __get_yamls(self,file_path):
     '''
     递归遍历读取文件夹下的yml文件
     :param file_path:
     :return:
     '''
     if os.path.isdir(file_path):
         files = [os.path.join(file_path,f)for f in os.listdir(file_path)]
         for f in files:
             if os.path.isfile(f) and f.endswith(".yml"):
                 self.yamls_dict[os.path.basename(f).split(".")[0]] = self.read_yaml(f)
             elif os.path.isdir(f):
                 self.__get_yamls(f)
     elif os.path.isfile(file_path):
         self.yamls_dict[os.path.basename(file_path).split(".")[0]] = self.read_yaml(file_path)
     else:
         log_tool.error("请输入正确的yaml文件夹")
         raise TypeError("direction is not right")
Example #2
0
def post_params(url, params=None, headers=None, cookies=None):
    headers = {}
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url,
                                 params=params,
                                 headers=headers,
                                 cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间,单位为毫秒
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Example #3
0
def put(url, data, header=None, cookies=None):
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        log_tool.debug(url)

    try:
        if data is None:
            response = requests.put(url=url, headers=header, cookies=cookies)
        else:
            response = requests.put(url=url, params=data, headers=header, cookies=cookies)

    except Exception as e:
        log_tool.error('%s%s' % ('RequestException url: ', url))
        log_tool.error(e)
        return ()
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response
Example #4
0
 def __init__(self, browser='chrome', timeout=10):
     '''
     :param browser: 浏览器类型
     :param timeout: 显示等待超时时间
     '''
     self.driver = None
     if browser == "firefox" or browser == "ff":
         self.driver = webdriver.Firefox()
     elif browser == "chrome":
         driver_path = ROOT_PATH
         self.driver = webdriver.Chrome(driver_path)
         self.driver.maximize_window()
         self.driver.implicitly_wait(10)
     elif browser == "internet explorer" or browser == "ie":
         self.driver = webdriver.Ie()
     elif browser == "opera":
         self.driver = webdriver.Opera()
     elif browser == "chrome_headless":
         chrome_options = Options()
         chrome_options.add_argument('--headless')
         self.driver = webdriver.Chrome(ROOT_PATH,
                                        chrome_options=chrome_options)
     elif browser == 'edge':
         self.driver = webdriver.Edge()
     else:
         log_tool.error(
             "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
             % browser)
         raise NameError(
             "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
             % browser)
     self.timeout = timeout
     self.location_type_dict = {
         "xpath": By.XPATH,
         "id": By.ID,
         "name": By.NAME,
         "css_selector": By.CSS_SELECTOR,
         "class_name": By.CLASS_NAME,
         "tag_name": By.TAG_NAME,
         "link_text": By.LINK_TEXT,
         "partial_link_text": By.PARTIAL_LINK_TEXT
     }
Example #5
0
def post_json(url, json=None, headers=None, cookies=None):
    if headers == None:
        headers = {}
    headers['content-type'] = 'application/json;;charset=UTF-8'
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url,
                                 headers=headers,
                                 json=json,
                                 cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间,单位为毫秒
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Example #6
0
 def click_by_js(self, locator):
     '''
     #通过xpath执行js代码点击元素
     :param locator: 定位语句 例如:xpath=>//*[@id='kw']
     :return:
     '''
     try:
         el = self.get_element(locator)
         loc = self.get_locator(locator)
         self.shot("使用js代码点击元素:", el)
         if (loc[0] == self.location_type_dict["xpath"]):
             js = "var xpath = \"" + self.double_to_single_mark(
             loc[1]) + "\";var element = document.evaluate(xpath,document,null,XPathResult.ANY_TYPE,null).iterateNext();element.click();"
             self.execute_script(js)
         else:
             message = "元素点击失败,请使用xpath定位,例如:xpath=>//*[@id='kw']"
             log_tool.error(message)
             raise TypeError(message)
     except:
         log_tool.error("点击元素失败:" + locator)
         raise
Example #7
0
    def get_locator(self, locator):
        '''
        解析定位关键字
        :param locator:定位语句 例如:xpath=>//*[@id='kw']
        :return: 元组(By.XPATH,"//*[@id='kw']")
        '''

        if "=>" not in locator and "xpath" not in locator:
            by = "xpath"
            value = locator
        elif ("=>" in locator):
            by = locator.split("=>")[0].strip()
            value = locator.split("=>")[1].strip()
            if by not in (self.location_type_dict):
                log_tool.error(
                    "%s中的定位方式错误,请输入正确的定位方式:"
                    "id,name,class_name,xpath,tag_name,css_selector,link_text,partial_link_text"
                    % (locator))
                raise TypeError(
                    "%s中的定位方式错误,请输入正确的定位方式:"
                    "id,name,class_name,xpath,tag_name,css_selector,link_text,partial_link_text"
                    % (locator))
            if by == "" or value == "":
                log_tool.error("%s格式错误,定位方式=>值 示例:'id=>useranme'" % (locator))
                raise NameError("%s格式错误,定位方式=>值 示例:'id=>useranme'" % (locator))
        else:
            log_tool.error("%s格式错误,定位方式=>值 示例:'id=>useranme'" % (locator))
            raise NameError("%s格式错误,定位方式=>值 示例:'id=>useranme'" % (locator))
        return (self.location_type_dict[by], value)
Example #8
0
 def get_element(self,locator):
     '''
     根据传入的数据来定位页面元素
     :param locator: 定位语句 例如:xpath=>//*[@id='kw']
     :return: 元素定位结果
     '''
     self.shot("定位元素",locator)
     local = self.get_locator(locator)
     try:
         el = WebDriverWait(BaseUI.driver, self.timeout).until(
             EC.presence_of_element_located(local))
         BaseUI.driver.execute_script("element = arguments[0];" +
     "original_style = element.getAttribute('style');" +
     "element.setAttribute('style', original_style + \";" +
     "background: yellow; border: 2px solid red;\");" +
     "setTimeout(function(){element.setAttribute('style', original_style);}, 1000);", el)
         return WebDriverWait(BaseUI.driver, self.timeout).until(
             EC.presence_of_element_located(local))
     except TimeoutException:
         time_out_error = "{}定位元素超时,请检查定为语句是否正确,或者尝试其他定位方式".format(local)
         log_tool.error(time_out_error)
         raise TimeoutException(time_out_error)
Example #9
0
 def update_attribute_by_xpath(self,locator,attribute_name,attribute_value):
     '''
     #通过xpath根据修改html标签属性的值
     :param locator: 定位语句 例如:xpath=>//*[@id='kw']
     :param attribute_name:属性名
     :param attribute_value: 属性值
     :return:
     '''
     try:
         el = self.get_element(locator)
         loc = self.get_locator(locator)
         self.shot("修改元素:",el,'属性:',attribute_name,'的值为:',attribute_value)
         if (loc[0] == self.location_type_dict["xpath"]):
             js = "var xpath = \"" + self.double_to_single_mark(
                 loc[1]) + "\";var element = document.evaluate(xpath,document,null,XPathResult.ANY_TYPE,null).iterateNext();element.setAttribute(\"" + attribute_name + "\",\"" + attribute_value + "\");"
             self.execute_script(js)
         else:
             message = "修改元素:{} 属性的值失败,请使用xpath定位,示例:xpath=>//*[@id='kw']"
             log_tool.error(message)
             raise TypeError(message)
     except:
         log_tool.error("修改属性值失败,属性名:" + attribute_name + " 属性值:" + attribute_value)
         raise
Example #10
0
def request(*args, **kwargs):
    '''
    Get请求
    :param url:
    :param data:
    :param header:
    :return:
    '''
    try:
        response = requests.request(*args, **kwargs)
    except requests.RequestException as e:
        log_tool.error('%s%s' % ('Exception url: ', kwargs['url']))
        log_tool.error(e)
        return ()
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', kwargs['url']))
        return ()
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Example #11
0
    def start_browser(self, browser='chrome'):
        '''
        启动浏览器
        :param browser: 浏览器类型
        '''
        if BaseUI.driver:
            log_tool.info("浏览器以启动,请勿再次启动浏览器。")
            return
        try:
            if browser == "firefox" or browser == "ff":
                BaseUI.driver = webdriver.Firefox()
            elif browser == "chrome":
                driver_path = DRIVER_PATH
                BaseUI.driver = webdriver.Chrome(driver_path)
                BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "internet explorer" or browser == "ie":
                BaseUI.driver = webdriver.Ie()
            elif browser == "opera":
                BaseUI.driver = webdriver.Opera()
            elif browser == "chrome_headless":
                chrome_options = Options()
                chrome_options.add_argument('--headless')
                BaseUI.driver = webdriver.Chrome(DRIVER_PATH,options=chrome_options)
            elif browser == "chrome_debugger":
                print("chrome_debugger模式")
                chrome_options = Options()
                chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9111")
                BaseUI.driver = webdriver.Chrome(DRIVER_PATH, options=chrome_options)
                # BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "mobile":
                print("mobile模式")
                # mobileEmulation = {'deviceName': 'Galaxy S5'}
                # chrome_options = webdriver.ChromeOptions()
                # chrome_options.add_experimental_option('mobileEmulation', mobileEmulation)
                # BaseUI.driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=chrome_options)
                WIDTH = 320
                HEIGHT = 640
                PIXEL_RATIO = 3.0
                UA = 'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3'
                mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO},"userAgent": UA}
                options = webdriver.ChromeOptions()
                options.add_experimental_option('mobileEmulation', mobileEmulation)
                BaseUI.driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=options)
                BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "headless":
                chrome_options = Options()
                # chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
                # chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
                # chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
                # 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\Google\Chrome\Application\chrome.exe"  # 手动指定本机电脑使用的浏览器位置

                # 创建一个driver,进行后面的请求页面等操作,executable_path指定本机中chromedriver.exe的位置
                BaseUI.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=DRIVER_PATH)

            elif browser == 'edge':
                BaseUI.driver = webdriver.Edge()
            else:
                log_tool.error("启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"% browser)
                raise NameError(
                    "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"% browser)
        except WebDriverException:
            log_tool.error("启动浏览器失败,请检查webdriver是否配置,或者webdriver版本是否和浏览器匹配")
            raise
        self.shot("-------测试开始,启动{}浏览器成功-------".format(browser))