s-yoshiki
3/24/2018 - 7:35 AM

selenimu

selenimu

from selenium import webdriver

from time import sleep
import os

class YahooAccountMgr():
	from selenium.webdriver.common.keys import Keys

	def __init__(self, _driver):
		self.driver = _driver
		self.func_history = ""

	def login(self, _id, _passwd):
		try:
			self.driver.get("http://yahoo.co.jp")
			self.driver.find_element_by_link_text("ログイン").click()
			sleep(1)
			self.driver.find_element_by_id("username").send_keys(_id)
			self.driver.find_element_by_id("btnNext").click()
			sleep(1)
			self.driver.find_element_by_id("passwd").send_keys(_passwd)
			self.driver.find_element_by_id("btnSubmit").click()
		except:
			traceError(obj)
			return False
		return True

	def logout(self):
		self.driver.get("https://login.yahoo.co.jp/config/login?logout=1")

	def execUserFunc(self,f ,*args):
		return f(driver)

	def traceError(self, obj):
		self.logout()

	def pushCallStacks(self, msg):
		self.func_history += msg
		self.func_history += "\n"

def getConfig(path):
	return [
		{'id' : 'XXXXXXXXXXX', 'password' : 'XXXXXXXXX'}
	]

def removeAllMails(m, conf):
	m.logout()
	m.login(conf['id'],conf['password'])
	m.driver.get("https://jp.mg5.mail.yahoo.co.jp/")
	# ゴミ箱
	try:
		m.driver.find_element_by_xpath("//input[@data-action='selectAll-message' and @title='すべてを選択/選択をはずす [Cmd+A]']").click()
		sleep(1)
		m.driver.find_element_by_xpath("//span[@id='h_delete']").click()
		sleep(1)
		m.driver.find_element_by_xpath("//span[@id='okModalOverlay']").click()
		sleep(25) #バックエンド処理待ち
	except:
		pass
	# 削除
	try:
		m.driver.find_element_by_xpath("//a[@aria-labelledby='trash-label trash-count']").click()
		m.driver.find_element_by_xpath("//span[@id='btn-emptytrash']").click()
		sleep(1)
		m.driver.find_element_by_xpath("//a[@data-action='ok']").click()
		sleep(10) #バックエンド処理待ち
	except:
		pass

	m.logout()
	return

def makeAccount(m, conf):
	pass

if __name__ == "__main__":
	# DRIVER
	# driver = webdriver.Chrome("./chromedriver.exe")
	driver = webdriver.Chrome()
	# driver = webdriver.Firefox()
	
	# CONFIG
	conf = getConfig('')

	m = YahooAccountMgr(driver)
	try:
		removeAllMails(m, conf[0])
	except:
		import traceback
		traceback.print_exc()
	finally:
		m.driver.close()
	
# coding: UTF-8
# pylint: disable=invalid-name

from selenium import webdriver
from time import sleep
import os
from PIL import Image

bs = webdriver.Firefox()
type(bs)
FILENAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "screen.png")

def main():

    bs.get('https://google.com/')
    bs.find_element_by_xpath("//*[@id='lst-ib']").send_keys("keywords")
    # sleep(1)
    bs.find_element_by_xpath("//*[@name='btnK']").click()
    sleep(2)
    bs.get('https://example.com/')
    sleep(2)
    bs.save_screenshot(FILENAME)
    bs_file_path = FILENAME.replace('\\', '/')
    bs_file_path = "file:///" + bs_file_path
    bs.get(bs_file_path)
    sleep(1)
    

    
    sleep(1)

main()
sleep(1)
main()
bs.quit()
im = Image.open(FILENAME)
im.show()
#coding : utf-8
from selenium import webdriver
from selenium.webdriver.support.ui import Select

#driver = webdriver.Firefox()
driver = webdriver.Chrome("/usr/bin/chromedriver")

target_url = "http://localhost/test.php"


def getFormStructure():
    form = {
        "text" : {
            "type"     : "text",
            "default"  : "abcdef123456",
            # "length"   : {"min" : 10,"max" : 20},
            # "required" : True,
            "exam"     : [
                "abcdefghijklmn",
                "1234567890123",
                "abc456789",
                "abc4567890",
                "+-*/<>()&#@[]",
                "ああああいいいいうううう",
                "",
            ]
        },
        "textarea" : {
            "type"     : "textarea",
            "default"  : "test",
            # "length"   : {"min" : 0,"max" : 50},
            # "required" : False
            "exam"     : [
                "abcdefghijklmn",
                "1234567890123",
                "abc456789",
                "abc4567890",
                "+-*/<>()&#@[]",
                "ああああいいいいうううう",
                "",
            ]
        },
        "radio" : {
            "type"     : "radio",
            "default"  : "1",
            # "range"    : ["1","2","3"],
            # "required" : False
            "exam"  : [
                "1","2","3",""
            ],
        },
        "selectbox" : {
            "type"     : "selectbox",
            "default"  : "a",
            # "range"    : ["a","b","c"],
            # "required" : True
        },
        "submit" : {
            "type"     : "button"
        }
    }
    return form

def fill_text(_type,key,value):
    textgrp = ["text","textarea"]
    clickgrp = ["radio","checkbox"]
    scrollgrp = ["selectbox"]

    if _type in textgrp:
        driver.find_element_by_name(key).clear()
        driver.find_element_by_name(key).send_keys(value)
    
    elif _type in clickgrp:
        xpath = "//input[@name='"+key+"' and @value='"+value+"']"
        driver.find_element_by_xpath(xpath).click()
    
    elif _type in scrollgrp:
        el = driver.find_element_by_name(key)
        selector = webdriver.support.ui.Select(el)
        selector.select_by_value(value)

def init_form(form):
    for key,val in form.items():
        if "default" in val:
            fill_text(val["type"],key,val["default"])

def check_window_type():
    return driver.find_element_by_tag_name('h1').text

def main():
    form = getFormStructure()
    for key,val in form.items():
        if "exam" not in val:
             continue
        for test_case in val["exam"]:
            try:
                driver.get(target_url)
                init_form(form)
                # event
                fill_text(val["type"],key,test_case)
                driver.find_element_by_name("submit").click()
                print(key+"\t"+test_case+"\t"+check_window_type())
            except :
                print("Exec Error \t"+key+"\t"+test_case+"\t")
    

if __name__ == "__main__":
    main()
#coding : utf-8
from selenium import webdriver
from selenium.webdriver.support.ui import Select

#driver = webdriver.Firefox()
driver = webdriver.Chrome("/usr/bin/chromedriver")
target_url = "http://localhost/test.php"

def getFormStructure():
    return {
        'default' : [
            # {'type':'text'    , 'name':'text',     'send':'aaaaaaaa123456'  ,'comment':'comment test'},
            # {'type':'textarea', 'name':'textarea', 'send':'aaaaaaaaaaaaaaaa'},
            # {'type':'radio'   , 'name':'radio',    'value':'1'              },
            # {'type':'checkbox', 'name':'checkbox', 'value':'0'              },
            # {'type':'select'  , 'name':'selectbox','value':'1'              },

            {'xpath':"//input[@name='text']",       'send':'aaaaaaaa123456','comment':'comment test'},
            {'xpath':"//input[@name='textarea']",   'send':'aaaaaaaaaaaaaaaa'},
            {'xpath':"//input[@name='radio' and @value='1']"},
            {'xpath':"//input[@name='checkbox' and @value='1']"},
            {'xpath':"//select[@name='select']/option[@value='1']"},
        ],
        'exam' : [
            {'type':'text'    , 'name':'text',     'send':'abcdefgh12345'   },
            {'type':'text'    , 'name':'text',     'send':'123456789'       },
            {'type':'text'    , 'name':'text',     'send':'aaaaaaaaaaaaaaaa'},
            {'type':'text'    , 'name':'text',     'send':'aaaaaaaaaaaaaaaa'},
            [

            ],
        ]
    }
<?php

$global_status = 0;
$global_err = array();

if(count($_POST) != 0){
    if($_POST['status'] == 'conf'){
        $global_err = check($_POST);
        if(count($global_err) == 0){
            $global_status = 2;
        }else{
            $global_status = 1;
        }
    }else if($_POST['status'] == 'conp'){
        $global_status = 3;
    }
    
}

function check($post){
    $f = getFormStructure();
    $errors = array();
    foreach ($f as $k => $v) {
        $err = array();
        $target = $post[$k];
        
        if($v["required"] == true){
            if($target == ""){
                $err["required"] = $target;
            }
        }
        if(isset($v["length"])){
            if(!inBoundary(mb_strlen($target),$v["length"]["min"],$v["length"]["max"])){
                $err["length"] = $target;
            }
        }
        if(isset($v["range"])){
            if(!in_array($target,$v["range"])){
                $err["range"] = $target;
            }
        }
        if(count($err) != 0){
            $errors[$k] = $err;
        }
    }
    return $errors;
}

function inBoundary($target,$min,$max){
    if($target<$max && $target>$min){
        return true;
    }
    return false;
}

function getFormStructure(){
    return array(
        "text" => array(
            "type"     => "text",
            "length"   => array("min" =>10,"max" => 20),
            "required" => true
        ),
        "textarea" => array(
            "type"     => "textarea",
            "length"   => array("min" =>0,"max" => 50),
            "required" => false
        ),
        "radio" => array(
            "type"     => "radio",
            "range"    => array("1","2","3"),
            "required" => false
        ),
        "selectbox" => array(
            "type"     => "selectbox",
            "range"    => array("a","b","c"),
            "required" => true
        )
    );
}

function getFormStr(){
    return "
    <form id='form' name='form' method='POST' action='/test.php'>
        <input type='hidden' name='status' value='conf'>
        <p><span class='required'>*</span> テキスト(10~20)</p>
        <input type='text' name='text' placeholder='text'>

        <p>複数行のテキスト(0~50)</p>
        <textarea name='textarea' cols='50' rows='5' placeholder='placeholder'></textarea>

        <p>ラジオボタン</p>
        <input type='radio' name='radio' value='1'>項目1
        <input type='radio' name='radio' value='2'>項目2
        <input type='radio' name='radio' value='3'>項目3

        <p>チェックボックス</p>
        <input type='checkbox' name='checkbox[]' value='1'>項目1
        <input type='checkbox' name='checkbox[]' value='2'>項目2
        <input type='checkbox' name='checkbox[]' value='3'>項目3
            
        <p><span class='required'>*</span> セレクトボックス</p>
        <select name='selectbox'>
            <option value=''>選択してください</option>
            <option value='a'>項目1</option>
            <option value='b'>項目2</option>
            <option value='c'>項目3</option>
        </select>
        <hr>
        <input name='submit' type='submit' value='送信'>
    </form>";
}

function getConfirmStr(){
    return "
    <form id='form' name='form' method='POST' action='/test.php'>
        <button type='submit' name='status' value='conp'>登録</button>
        <button type='submit' name='status' value='conf'>戻る</button>
    <form>
    ";
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
    .required {
        color:#DD3333;
    }
    </style>
</head>
<body>
<?php 

if($global_status == 0){
    echo "<h1 id='head'>入力画面</h1>";
    echo(getFormStr());
}else if($global_status == 1){
    echo "<h1 id='head'>入力画面</h1>";
    echo "<h3>エラーがあります</h3>";
    echo(getFormStr());
    echo("<hr>");
    var_dump($global_err);
}else if($global_status == 2){
    echo "<h1 id='head'>確認画面</h1>";
    echo(getConfirmStr());
    echo("<hr>");
}else if($global_status == 3){
    echo "<h1 id='head'>完了画面</h1>";
    echo "<a href='/test.php'>TOPへ</a>";
}

?>
</body>
</html>