Appium_python code(2)

44756 단어 Selenium
# coding:utf8
import logging
import histsimilar
import traceback
import time
import os
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, WebDriverException

logging.basicConfig(filename='log.txt',level=logging.INFO)
success = True
desired_caps = dict()
desired_caps['browserName'] = 'iOS'
desired_caps['platform'] = 'Mac'
desired_caps['version'] = '6.1'
desired_caps['app'] = os.path.abspath('  app   ')

#def is_alert_present(wd):
#    try:
#        wd.switch_to_alert().text
#        return True
#    except:
#        return False



def click(element):
    element.click()
    time.sleep(3)
    logging.info(str(c) + ' time click ' + wd.page_source)
    screenshot()


def send_keys(element, keys):
    element.send_keys(keys)
    time.sleep(3)
    logging.info(str(c) + ' time click ' + wd.page_source)
    screenshot()


def execute_script(script, args):
    wd.execute_script(script, args)
    time.sleep(3)
    screenshot()


def mk_new_dir():
    global path, base
    base = '       '
    if not os.path.isdir(base):
        path = base + '0/'
        os.mkdir(path)
        return
    path = base + str(len(os.listdir(base))) + '/'


c = 0


def screenshot():
    global c, path
    if not os.path.isdir(path):
        os.mkdir(path)
    wd.get_screenshot_as_file(path + str(c) + '.png')
    c += 1


def compare():
    dirs = list()
    for dirname in os.listdir(base):
        if os.path.isdir(base + dirname):
            dirs.append((os.path.getmtime(base + dirname), dirname))
    if len(dirs) < 3:
        return
    dirs.sort()
    new = dirs[len(dirs) - 1][1]
    previous = dirs[len(dirs) - 2][1]
    names = [(os.path.getmtime(base + new + '/' + filename), filename) for filename in
             os.listdir(base + new)]
    names.sort()
    for n in names:
        if n[1].startswith('.'):
            continue
        if os.path.exists(base + previous + '/' + n[1]):
            print n[1] + ' similarity : ' + str(
                int(histsimilar.calc_similar_by_path(base + new + '/' + n[1],
                                                     base + previous + '/' + n[1]) * 100)) + '%'


try:
    mk_new_dir()
    wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
    wd.implicitly_wait(5)
    try:
        button = wd.find_element_by_name('    ')
        while not button.is_displayed():
            #screenshot()
            time.sleep(1)
        time.sleep(3)
        click(button)
    except WebDriverException, NoSuchElementException:
        logging.info('      ')
    click(wd.find_element_by_xpath("//window[1]/tableview[1]/cell[1]/button[1]"))
    click(wd.find_element_by_name("   "))
    click(wd.find_element_by_xpath("//window[1]/tableview[1]/cell[1]/button[2]"))
    click(wd.find_element_by_name("   "))
    click(wd.find_element_by_name("  "))
    click(wd.find_element_by_name("qunar login"))
    send_keys(wd.find_element_by_xpath("//window[1]/image[2]/textfield[1]"), "[email protected]")
    send_keys(wd.find_element_by_xpath("//window[1]/image[3]/secure[1]"), "[email protected]")
    click(wd.find_element_by_name("  "))
    try:
        click(wd.find_element_by_xpath("//window[1]/button[3]"))
    except:
        logging.info('     ')
    click(wd.find_element_by_xpath("//window[1]/tableview[1]/cell[1]/text[1]"))
    click(wd.find_element_by_xpath("//window[1]/tableview[1]/cell[1]"))
    execute_script("mobile: swipe",
                   {"touchCount": 1, "startX": 157, "startY": 529, "endX": 156, "endY": 102, "duration": 0.5})
    click(wd.find_element_by_name("   "))
    click(wd.find_element_by_name("   "))
    click(wd.find_element_by_xpath("//window[1]/button[1]"))
except:
    traceback.print_exc()
    success = False
finally:
    if success:
        #raise Exception("Test failed.")
        compare()
        wd.quit()
         
# -*- coding: utf-8 -*-

import Image


def make_regalur_image(img, size=(256, 256)):
    return img.resize(size).convert('RGB')


def split_image(img, part_size=(64, 64)):
    w, h = img.size
    pw, ph = part_size

    assert w % pw == h % ph == 0

    return [img.crop((i, j, i + pw, j + ph)).copy() \
            for i in xrange(0, w, pw) \
            for j in xrange(0, h, ph)]


def hist_similar(lh, rh):
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lh, rh)) / len(lh)


def calc_similar(li, ri):
#   return hist_similar(li.histogram(), ri.histogram())
    return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0


def calc_similar_by_path(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    return calc_similar(li, ri)


def make_doc_data(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    li.save(lf + '_regalur.png')
    ri.save(rf + '_regalur.png')
    fd = open('stat.csv', 'w')
    fd.write('
'.join(l + ',' + r for l, r in zip(map(str, li.histogram()), map(str, ri.histogram())))) # print >>fd, '
'
# fd.write(','.join(map(str, ri.histogram()))) fd.close() import ImageDraw li = li.convert('RGB') draw = ImageDraw.Draw(li) for i in xrange(0, 256, 64): draw.line((0, i, 256, i), fill='#ff0000') draw.line((i, 0, i, 256), fill='#ff0000') li.save(lf + '_lines.png')

좋은 웹페이지 즐겨찾기