python+selenium常用方法

class Action(object):
def init(self,driver):
self.driver=driver

def open(self, url, title, timeout=10):
    u"""打开浏览器,并最大化,判断title是否为预期"""
    self.driver.get(url)
    self.driver.maximize_window()
    try:
        WebDriverWait(self.driver, timeout, 1).until(EC.title_contains(title))
    except TimeoutException:
        print("open %s title error" % url)
    except Exception as msg:
        print("Error:%s" % msg)

def js_scale(self,value):
    u'''控制浏览器缩编'''
    #js="document.body.style.transform='scale('"+str(value)+"')'"
    js = "document.body.style.zoom=" + str(value)
    self.driver.execute_script(js)

def get_windows_img(self):
    file_path = os.getcwd().replace('\\','/')+'/reports/'
    rq = time.strftime('%Y-%m-%d_%H.%M.%S')
    filename = file_path + rq + '.jpg'
    try:
        self.driver.get_screenshot_as_file(filename)
        logger.info('截图成功保存在screenshots目录下')
    except NameError as e:
        logger.error('截图失败:%s' % e)

def split_locator(self, selector):
    if '=>' not in selector:
        return self.driver.find_element_by_id(selector)
    selector_by = selector.split('=>')[0]
    selector_value = selector.split('=>')[1]
    if selector_by == "i" or selector_by == 'id':
        locator = (By.ID, selector_value)
    elif selector_by == "n" or selector_by == 'name':
        locator = (By.NAME, selector_value)
    elif selector_by == "c" or selector_by == 'class_name':
        locator = (By.CLASS_NAME, selector_value)
    elif selector_by == "l" or selector_by == 'link_text':
        locator = (By.LINK_TEXT, selector_value)
    elif selector_by == "p" or selector_by == 'partial_link_text':
        locator = (By.PARTIAL_LINK_TEXT, selector_value)
    elif selector_by == "t" or selector_by == 'tag_name':
        locator = (By.TAG_NAME, selector_value)
    elif selector_by == "x" or selector_by == 'xpath':
        locator = (By.XPATH, selector_value)
    elif selector_by == "s" or selector_by == 'selector_selector':
        locator = (By.CSS_SELECTOR, selector_value)
    else:
        raise NameError("Please enter a valid type of targeting element.")
    return locator

# 定位元素方法
def find_element(self, selector):
    """
     submit_btn = "id=>su"
     login_lnk = "xpath => //*[@id='u1']/a[7]"  # 百度首页登录链接定位
    :param selector:
    :return: element
    """
    locator = self.split_locator(selector)
            try:
        element = WebDriverWait(self.driver, 20, 0.5).until(EC.presence_of_element_located((locator)))
        logger.info("Had find the element \' %s \' successful "
                        "by %s via value: %s " % (element.text,selector))
    except NoSuchElementException as e:
        logger.error("NoSuchElementException: %s" % e)
        self.get_windows_img()  # take screenshot
    return element
    
def find_elements(self, selector, timeout=10):
    u"""定位一组元素"""
    locator = self.split_locator(selector)
    elements = WebDriverWait(self.driver, 5, 0.5).until(
        EC.presence_of_all_elements_located((By.ID, locator)))
    return elements

def send_key(self, locator, text):
u""“发送文本后清除内容”""
element = self.find_element(locator)
element.clear()
element.send_keys(text)

def is_text_in_element(self, text, selector, timeout=10):
    u"""判断是否定位到元素"""
    locator = self.split_locator(selector)
    try:
        result = WebDriverWait(self.driver, timeout, 1).until(EC.text_to_be_present_in_element(locator, text))
    except TimeoutException:
        print(u"元素未定位到:" + str(locator))
        return False
    else:
        return result

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

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

def is_select(self, locator, timeout=10):
    u"""判断元素是否被选中"""
    locator = self.split_locator(locator)
    result = WebDriverWait(self.driver, timeout, 1).until(EC.element_located_to_be_selected(locator))
    return result

def is_select_be(self, locator, timeout=10, selected=True):
    u"""判断元素的状态"""
    locator = self.split_locator(locator)
    return WebDriverWait(self.driver, timeout, 1).until(
        EC.element_located_selection_state_to_be(locator, selected))

def is_alert_present(self, timeout=10):
    u"""判断页面有无alert弹出框,有alert返回alert,无alert返回FALSE"""
    try:
        return WebDriverWait(self.driver, timeout, 1).until(EC.alert_is_present())
    except:
        print("No Alert Present")

def switch_alert(self,timeout=10):
    u'''关闭弹窗'''
    alert = self.driver.switch_to_alert()
    alert.accept()

def is_visibility(self, locator, timeout=10):
    u"""判断元素是否可见,可见返回本身,不可见返回FALSE, locator = 'By.ID,id_name'"""
    locator = self.split_locator(locator)
    element = WebDriverWait(self.driver, timeout, 1).until(EC.visibility_of_element_located(locator))
    return element

def is_invisibility(self, locator, timeout=10):
    u"""判断元素是否可见,不可见,未找到元素返回True"""
    locator = self.split_locator(locator)
    return WebDriverWait(self.driver, timeout, 1).until(EC.invisibility_of_element_located(locator))

def is_clickable(self, locator, timeout=10):
    u"""判断元素是否可以点击,可以点击返回本身,不可点击返回FALSE"""
    locator = self.split_locator(locator)
    return WebDriverWait(self.driver, timeout, 1).until(EC.element_to_be_clickable(locator))

def is_text(self,locator,text,timeout=2):
    u'''判断文本,匹配返回True,否则返回False;text是期望值'''
    locator = self.split_locator(locator)
    return WebDriverWait(self.driver, timeout, 1).until(EC.text_to_be_present_in_element_value(locator,text))

def is_located(self, locator, timeout=10):
    u"""判断元素是否定位到(元素不一定是可见),如果定位到返回Element,未定位到返回FALSE"""
    locator = self.split_locator(locator)
    element = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator))
    return element

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

def back(self):
    u"""返回到旧的窗口"""
    self.driver.back()

def forward(self):
    u"""前进到新窗口"""
    self.driver.forward()

def close(self):
    u"""关闭窗口"""
    self.driver.close()

def quit(self):
    u"""关闭driver和所有窗口"""
    self.driver.quit()

def get_title(self):
    u"""获取当前窗口的title"""
    return self.driver.title

def get_current_url(self):
    u"""获取当前页面url"""
    return self.driver.current_url

def get_text(self, locator):
    u"""获取文本内容"""
    return self.find_element(locator).text

def get_browser_log_level(self):
    u"""获取浏览器错误日志级别"""
    lists = self.driver.get_log('browser')
    list_value = []
    if lists.__len__() != 0:
        for dicts in lists:
            for key, value in dicts.items():
                list_value.append(value)
    if 'SEVERE' in list_value:
        return "SEVERE"
    elif 'WARNING' in list_value:
        return "WARNING"
    return "SUCCESS"

def switch_frame(self,locator):
    u'''frame切换'''
    element = self.find_element(locator)
    self.driver.switch_to_frame(element)

def switch_default_frame(self):
    self.driver.switch_to_default_content()

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

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

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

def del_element(self,selector):
    u'''删除页面元素'''
            if '=>' not in selector:
        return self.driver.find_element_by_id(selector)
    selector_by = selector.split('=>')[0]
    selector_value = selector.split('=>')[1]
    if selector_by == "i" or selector_by == 'id':
        js = "document.getElementById(\"" + selector_value + "\").remove()"
    elif selector_by == "n" or selector_by == 'name':
        js = "document.getElementByName(\"" + selector_value + "\").remove()"
    elif selector_by == "c" or selector_by == 'class_name':
        js = "document.getElementByClassName(\"" + selector_value + "\").remove()"
    elif selector_by == "t" or selector_by == 'tag_name':
        js = "document.getElementByTagName(\"" + selector_value + "\").remove()"
    else:
        raise NameError("Please enter a valid type of targeting elements.")
    self.driver.execute_script(js)

def js_scroll_top(self):
    u"""滑动到页面顶部"""
    js = "window.scrollTo(0,0)"
    self.driver.execute_script(js)

def js_scroll_end(self):
    u"""滑动到页面底部"""
    js = "window.scrollTo(0, document.body.scrollHeight)"
    self.driver.execute_script(js)

def js_scroll_value(self,scroll):
    u"""滑动指定距离"""
    js = "document.documentElement.scrollTop='%s'" %scroll
    self.driver.execute_script(js)

def select_by_index(self, locator, index):
    u"""通过所有index,0开始,定位元素"""
    element = self.find_element(locator)
    Select(element).select_by_index(index)

def get_location(self,locator):
    u'''获取元素坐标'''
    element = self.find_element(locator)
    location = element.location
    size = element.size
    return (location,size)

def cal_diff_img(self,locator1,locator2):
    u'''计算滑块得位置,适用于滑块 与 原图 两个图片,获取坐标计算差值'''
    print(self.get_location(locator1)[0])
    img1_x = self.get_location(locator1)[0]
    img2_x = self.get_location(locator2)[0]
    x1=int(str(img1_x['x']))
    x2=int(str(img2_x['x']))
    return(abs(x1-x2))

def verify_image(self,locator1,diff_val):
    u'''破解滑块验证码'''
    slide_btn=self.find_element(locator1)
    action = ActionChains(self.driver)
    action.click_and_hold(on_element=slide_btn).perform()
    action.reset_actions()
    action.move_by_offset(xoffset=diff_val,yoffset=0).perform()
    time.sleep(1)
    action.reset_actions()
    action.release(on_element=slide_btn).perform()
    time.sleep(0.5)

def get_verify_code(self, locator):
    u"""获取图片验证码"""
    # 验证码图片保存地址
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    screenImg = os.getcwd() + '\\report\\' + now_time + ".png"

    # 浏览器页面截图
    self.driver.get_screenshot_as_file(screenImg)

    # 定位验证码大小
    location = self.find_element(locator).location
    size = self.find_element(locator).size
    # 定位验证码图片截图
    # pic = self.find_element(locator)
    # pic.screenshot(screenImg)
    left = location['x']
    top = location['y']
    right = location['x'] + size['width']
    bottom = location['y'] + size['height']

    # 从文件读取截图,截取验证码位置再次保存
    img = Image.open(screenImg).crop((left, top, right, bottom))
    img.convert('L')  # 转换模式:L|RGB
    img = ImageEnhance.Contrast(img)  # 增加对比度
    img = img.enhance(2.0)  # 增加饱和度
    img.save(screenImg)

    # 再次读取验证码
    img = Image.open(screenImg)
    time.sleep(1)
    code = pytesseract.image_to_string(img,lang ='eng')
    return code

def get_pic_code(self,locator):
    """ 你的 APPID AK SK """
    APP_ID = '***'
    API_KEY = '****'
    SECRET_KEY = '*****'
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    now_time = time.strftime('%H-%M-%S', time.localtime())
    #screenImg = 'D:\\pic\\' + now_time + ".png"
    screenImg = '/media/xuxin/data/pic/'+now_time+".png"
    # 浏览器页面截图
    self.driver.get_screenshot_as_file(screenImg)
    # 定位验证码图片截图
    #pic = self.find_element(locator)
    #pic.screenshot(screenImg)
    # 从文件读取截图,截取验证码位置再次保存
    # 定位验证码大小 .crop((420, 470, 500, 510))
    img = Image.open(screenImg).crop((420, 400, 500, 430))
    img.convert('L')  # 转换模式:L|RGB
    enhancer = ImageEnhance.Color(img)
    enhancer = enhancer.enhance(2)
    enhancer = ImageEnhance.Contrast(enhancer)
    img = enhancer.enhance(20)
    img.save(screenImg)
    options = {}
    options["language_type"] = "ENG"
    f = open(screenImg, 'rb')
    code = client.basicAccurate(f.read(), options)['words_result']
    return code
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值