자동화
-
파이썬과 자바 selenium 사용법 간단한 기능 비교 및 xpath 사용법2018.08.08
-
파이썬에서 selenium을 이용하여 크롬 브라우저 띄우기2018.08.07
-
Selenium 을 이용한 버거킹 영수증 설문조사 자동화2016.07.25
-
Appium 자동화 상하좌우 스크롤 하기2016.03.23
파이썬과 자바 selenium 사용법 간단한 기능 비교 및 xpath 사용법
JAVA
driver.manage().window().maximize(); //브라우저 확장
Python
driver.maximize_window()
JAVA
Thread.sleep(500); //단위 ms
Python
import time #(import 필요)
time.sleep(0.5) # 단위 s
JAVA
Alert alert = driver.switchTo().alert(); //얼럿 창으로 스위칭
Python
alert = driver.switch_to_alert()
JAVA
alertText = alert.getText(); //얼럿 창 메시지 추출
Python
alertText = alert.text
JAVA
driver.find_element_by_id('user_id').sendKeys('id'); //id 요소 찾기와 입력값 채우기
Python
driver.find_element_by_id('user_id').send_keys('id')
JAVA
driver.quit();
Python
driver.close()
Python
driver.find_element_by_xpath('//*[@id="content"]/div/div[3]/button[2]').click() //xpath 클릭
표 출처 : https://wkdtjsgur100.github.io/selenium-xpath/
'지식메모 > Python' 카테고리의 다른 글
python 3.7.0 에서 pyside2를 설치하여 Qt Designer 설치하기 (2) | 2018.08.14 |
---|---|
파이썬에서 selenium으로 네이버 로그인 자동화하기 (0) | 2018.08.08 |
파이썬 TabError: inconsistent use of tabs and spaces in indentation 에러 해결 (Atom 에디터 옵션 설정) (0) | 2018.08.08 |
파이썬에서 selenium을 이용하여 크롬 브라우저 띄우기 (0) | 2018.08.07 |
android calabash apk is not signed with any of the available keystores 문제 해결을 위한 apk resign 하기 (0) | 2015.05.29 |
파이썬에서 selenium을 이용하여 크롬 브라우저 띄우기
사전 작업이 필요(환경변수에 파이썬도 추가되어있는 상태)
크롬드라이버 내려받기
https://sites.google.com/a/chromium.org/chromedriver/downloads
경로는 편한 곳으로 내려받기
멋 모르고 파일명을 selenium으로 해놨다가 삽질함
from selenium import webdriver driver = webdriver.Chrome('C://chromedriver.exe') driver.implicitly_wait(3) driver.get('http://www.naver.com')
위 코드를 작성하고 파이썬 실행
'지식메모 > Python' 카테고리의 다른 글
파이썬과 자바 selenium 사용법 간단한 기능 비교 및 xpath 사용법 (0) | 2018.08.08 |
---|---|
파이썬 TabError: inconsistent use of tabs and spaces in indentation 에러 해결 (Atom 에디터 옵션 설정) (0) | 2018.08.08 |
android calabash apk is not signed with any of the available keystores 문제 해결을 위한 apk resign 하기 (0) | 2015.05.29 |
이클립스에서 Ruby 플러그인 추가하기 (2) | 2015.05.19 |
윈도우 7 Ruby 설치하기 & Android calabash 설치 후 apk 실행하기 (0) | 2015.05.15 |
Selenium 을 이용한 버거킹 영수증 설문조사 자동화
버거킹 영수증을 받아보면 하단에 설문조사코드가 있습니다.
설문을 마치면 단품으로 세트를 먹을 수 있는 코드를 발급받게 되는데요
설문조사를 하는 것도 은근히 시간이 걸리는 것 같아 한번 시도해보았습니다.
Selenium 을 사용하였고 스윙으로 UI를 대충 만들어보았습니다.
설문이 끝나면 발급코드가 표시되는 간단한 프로그램입니다.
자바 환경 설치가 필수로 되어 있어야 하며
C: 또는 D: 드라이브 경로에
chromedriver.exe가 존재해야 합니다.
시연 영상
셀레니움 부분 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | package com.burger.king; import java.io.File; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import static com.codeborne.selenide.Selenide.*; import static com.codeborne.selenide.Condition.*; @FixMethodOrder (MethodSorters.NAME_ASCENDING) public class survey { private static WebDriver driver; static String receiptNum=""; static String url="https://kor.tellburgerking.com"; public void inputNumber(String number){ // 텍스트 필드값 가져오기 receiptNum = number; } @BeforeClass public static void setUp() throws Exception { File file = new File("c:/chromedriver.exe"); File file2 = new File("d:/chromedriver.exe"); if(file.isFile()){ System.setProperty("webdriver.chrome.driver", "c:/chromedriver.exe"); //크롬 드라이버 파일 경로설정 }else if(file2.isFile()){ System.setProperty("webdriver.chrome.driver", "d:/chromedriver.exe"); //크롬 드라이버 파일 경로설정 }else{ //안내문 runner.labelIntroduce.setText("C 또는 D드라이브에 chromedriver가 없습니다.\n"); } driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //응답시간 5초설정 driver.get(url); driver.manage().window().maximize(); } public static void login() throws InterruptedException { boolean boo = true; WebElement NextButton = driver.findElement(By.id("NextButton")); NextButton.click(); driver.findElement(By.id("CN1")).sendKeys(receiptNum); //ID Thread.sleep(1000); driver.findElement(By.id("NextButton")).click(); int i = 0; while(boo){ try{ boolean radioButtonHolder = driver.findElements(By.className("radioButtonHolder")).size() > 0; boolean checkboxBranded = driver.findElements(By.className("checkboxBranded")).size() > 0; boolean radioBranded = driver.findElements(By.className("radioBranded")).size() > 0; boolean checkCode = driver.findElements(By.className("ValCode")).size() > 0; boolean Next = driver.findElements(By.id("NextButton")).size() > 0; if(radioButtonHolder){ driver.findElement(By.className("radioButtonHolder")).click(); } else if(checkboxBranded){ driver.findElement(By.className("checkboxBranded")).click(); } else if(radioBranded){ driver.findElement(By.className("radioBranded")).click(); } if(Next) driver.findElement(By.id("NextButton")).click(); if(checkCode) boo = false; System.out.println(i++); }catch (NoSuchElementException e){ } } String checkCode = driver.findElement(By.xpath("//*[@id='FNSfinishText']/div/p[2]")).getText(); runner.labelIntroduce.setText(checkCode); } @Test public static void run() throws Exception { login(); Thread.sleep(500); } @AfterClass public static void tearDown() throws Exception { driver.quit(); } } | cs |
스윙UI 부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | package com.burger.king; import javax.swing.*; import com.burger.king.runner; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; class runner extends Thread{ Simulator simul = new Simulator(); public static JLabel labelIntroduce; public static survey survey = new survey(); public static JTextField tf_receiptNum; public static JLabel submit,number; public boolean check = true; public void run(){ // 텍스트 필드값 가져오기 String receiptNum = tf_receiptNum.getText(); try { survey.setUp(); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } survey.inputNumber(receiptNum); try { survey.run(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } class JPanel033 extends JPanel{ runner thread = new runner(); // 클래스 멤버 필드 설정 private JLabel name; private JLabel id; private JButton buttonSave; private JButton buttonStop; public boolean check = true; public JPanel033() { setLayout(null); // 라벨 name = new JLabel("by. yonoo"); name.setSize(100, 20); name.setLocation(2, 0); id = new JLabel("설문조사코드: "); id.setBounds(10,30,100,20); // 텍스트 필드 runner.tf_receiptNum = new JTextField(); runner.tf_receiptNum.setBounds(100,30,200,20); thread.labelIntroduce = new JLabel("="); thread.labelIntroduce.setBounds(10,50,280,20); // 버튼 buttonSave = new JButton("시작"); buttonSave.setBounds(80,80,100,20); buttonSave.addActionListener(new EventHandlerSave()); buttonStop = new JButton("정지"); buttonStop.setBounds(220,80,100,20); buttonStop.addActionListener(new EventHandlerStop()); add(name); add(thread.labelIntroduce); add(id); add(thread.tf_receiptNum); add(buttonSave); add(buttonStop); } class EventHandlerSave implements ActionListener{ // public void actionPerformed(ActionEvent e){ // try { // thread.start(); // } catch (Exception e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } if(check){ thread.start(); }else{ runner thread = new runner(); thread.start(); check = true; } } } class EventHandlerStop implements ActionListener{ // public void actionPerformed(ActionEvent e){ check = false; System.out.println(check); thread.interrupt(); System.out.println("정지!"); // System.exit(1); } } } public class Simulator extends JFrame{ public JPanel033 jpanel03 = null; public static void main(String[] args) { Simulator win = new Simulator(); win.setTitle("BurgerKing Survey Automation"); win.jpanel03 = new JPanel033(); URL imageURL = Simulator.class.getClassLoader().getResource("burger.png"); System.out.println(imageURL); ImageIcon img = new ImageIcon(imageURL); win.setIconImage(img.getImage()); win.add(win.jpanel03); win.setSize(400,150); win.setVisible(true); win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } | cs |
'지식메모 > 자동화' 카테고리의 다른 글
python과 java 에서 selenium 으로 크롬 자동화시 chromedriver.exe 프로세스 죽이기 (1) | 2018.12.30 |
---|---|
Rest-assured를 사용하여 간단한 Naver Open API 테스트 (0) | 2017.03.13 |
REST-Assured 를 사용하여 maven 프로젝트로 간단한 API 테스트 (0) | 2016.07.20 |
테스터로서 느낀 4가지 실수들 (0) | 2016.06.14 |
appium 에서 특정영역을 좌우로 swipe 하기 (2) | 2016.05.23 |
Appium 자동화 상하좌우 스크롤 하기
swipe를 이용한 상하좌우 스크롤 및 스크롤 새로고침 구현
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import io.appium.java_client.AppiumDriver; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.NoSuchElementException; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; //import org.junit.Test; import org.testng.annotations.Test; public class Utilities extends AndroidDriver<WebElement> implements TakesScreenshot { Dimension size = manage().window().getSize(); /** * 위로 스크롤 */ public void scrollUp() throws Exception { Thread.sleep(2000); int starty = (int) (size.height * 0.80); int endy = (int) (size.height * 0.20); int startx = size.width / 2; System.out.println("startx = " + startx + " ,endy = " + endy + " , starty = " + starty); //올리기 this.swipe(startx, endy, startx, starty, 0); Thread.sleep(2000); } /** * 아래로 스크롤 */ public void scrollDown() throws Exception { Thread.sleep(2000); int starty = (int) (size.height * 0.80); int endy = (int) (size.height * 0.20); int startx = size.width / 2; // System.out.println("startx = " + startx + " ,endy = " + endy + " , starty = " + starty); //내려가기 swipe(startx, starty, startx, endy, 0); Thread.sleep(2000); } /** * 스크롤 새로고침 */ public void pullToRefresh() throws Exception { Thread.sleep(1000); int starty = (int) (size.height * 0.5); int endy = (int) (size.height * 0.9); int startx = (int) (size.width*0.01); // System.out.println("startx = " + startx + " ,endy = " + endy + " , starty = " + starty); //내려가기 swipe(startx, starty, startx, endy, 0); Thread.sleep(2000); } /** * 오른쪽에서 왼쪽으로 Swipe */ public void swipeToLeft() throws Exception { Thread.sleep(2000); int starty = (int) (size.width * 0.80); int endx = (int) (size.width * 0.20); int startx = size.height / 2; swipe(startx, starty, endx, starty, 0); Thread.sleep(2000); } /** * 왼쪽에서 오른쪽으로 Swipe */ public void swipeToRight() throws Exception { Thread.sleep(2000); int starty = (int) (size.width * 0.80); int endx = (int) (size.width * 0.20); int startx = size.height / 2; swipe(endx, starty, startx, starty, 0); Thread.sleep(2000); } } | cs |
'지식메모 > 자동화' 카테고리의 다른 글
테스터로서 느낀 4가지 실수들 (0) | 2016.06.14 |
---|---|
appium 에서 특정영역을 좌우로 swipe 하기 (2) | 2016.05.23 |
Robotium API 기능 알아보기 (0) | 2016.02.18 |
로보티움 튜토리얼 실행해보기 (0) | 2015.09.04 |
Selenium & Webdriver 자동화 테스트 예제 - Naver 지식인 (크롬 브라우저) (0) | 2015.01.23 |
Selenium & Webdriver 자동화 테스트 예제 - Naver 지식인 (크롬 브라우저)
셀레니움 JAVA 버전 jar 라이브러리 다운로드 후 프로젝트에 추가
http://docs.seleniumhq.org/download/
2.44.0 클릭하여 다운로드
프로젝트에 추가하는 방법
프로젝트 우클릭 > Properties > Java Build Path > Add External JARs.. 클릭 후 해당 라이브러리 선택하여 추가
크롬브라우저 용 드라이버 파일
실행 동영상
소스코드
package work2; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; @FixMethodOrder (MethodSorters.NAME_ASCENDING) public class INTest { private static WebDriver driver; String Title = null; String URL = null; String alertText = ""; @BeforeClass public static void setUp() throws Exception { System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe"); //크롬 드라이버 파일 경로설정 driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //응답시간 5초설정 driver.get("http://www.naver.com"); //접속할 사이트 } @Test public void Step_01_지식인_로그인_Test () throws Exception { driver.findElement(By.id("svc.kin")).click(); //지식인 클릭 driver.findElement(By.id("login_btn")).click(); //NAVER로그인 클릭 driver.findElement(By.id("id")).sendKeys("ID"); //ID driver.findElement(By.id("pw")).sendKeys("PASSWORD"); //비번 driver.findElement(By.className("int_jogin")).click(); //로그인 버튼 클릭 } @Test public void Step_02_임시저장_Test () throws Exception { for(String Handle : driver.getWindowHandles()) //새창으로 스위칭 driver.switchTo().window(Handle); driver.findElement(By.xpath("//*[@id='main_top_2']/div[1]/fieldset[1]/div/a/img")).click();//질문하기 클릭 driver.switchTo().frame("editor"); //질문하기 입력창 iframe으로 스위칭 driver.findElement(By.xpath("//*[@id='title']")).sendKeys("원투쓰리포"); //제목입력 driver.switchTo().frame("SmartEditorIframe"); //내용입력 창 iframe 스위칭 driver.findElement(By.cssSelector("body")).sendKeys("일이삼사"); //내용입력 driver.switchTo().defaultContent(); //스위칭 초기화 //다시 질문하기 창 iframe 스위칭 driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='editor']"))); driver.findElement(By.xpath("//*[@id='au_submit_button']/div[2]/a[1]/img")).click(); //임시저장 클릭 String num = driver.findElement(By.id("temporary_save_count")).getText(); //현재 임시저장 글 수 카운트 추출 Thread.sleep(1000); //너무 빨라 얼럿 창 노출이 안되는 걸 방지하기 위해 슬립 추가 Alert alert = driver.switchTo().alert(); //얼럿 창으로 스위칭 alertText = alert.getText(); //얼럿 창 메시지 추출 alert.accept(); //얼럿 창 확인 클릭 System.out.println(alertText); //얼랏 창 메시지 출력 Thread.sleep(1000); System.out.println("임시저장 글 개수 : "+num); driver.findElement(By.xpath("//*[@id='title']")).clear(); //질문 제목 삭제 driver.findElement(By.xpath("//*[@id='title']")).sendKeys("파이브식스세븐에잇"); //질문 다시 입력 driver.switchTo().frame("SmartEditorIframe"); //내용 입력 창 iframe 스위칭 driver.findElement(By.cssSelector("body")).sendKeys("오육칠팔"); //내용입력 driver.switchTo().defaultContent(); //창 스위칭 초기화 //다시 질문하기 창 iframe 스위칭 driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='editor']"))); Thread.sleep(1000); } @Test public void Step_03_다음단계_Test () throws Exception { driver.findElement(By.xpath("//img[@alt='다음단계']")).click(); //다음단계 버튼 클릭 //카테고리 Thread.sleep(1000); driver.findElement(By.linkText("디렉토리 직접 선택")).click(); //디렉토리 직접선택 클릭 Select dropdown = new Select(driver.findElement(By.id("choose_dir_d1"))); //첫번째 셀렉 박스를 가져옴 dropdown.deselectAll(); //선택 모두 초기화 dropdown.selectByValue("1"); //value 1인 값을 선택 dropdown = new Select(driver.findElement(By.id("choose_dir_d2"))); //두번째 셀렉박스 가져옴 dropdown.deselectAll(); //이하 동일 dropdown.selectByValue("101"); dropdown = new Select(driver.findElement(By.id("choose_dir_d3"))); dropdown.deselectAll(); dropdown.selectByValue("10103"); dropdown = new Select(driver.findElement(By.id("choose_dir_d4"))); dropdown.deselectAll(); dropdown.selectByValue("1010303"); Thread.sleep(1000); driver.switchTo().defaultContent(); //창 스위칭 초기화 //질문하기 창 iframe 스위칭 driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='editor']"))); driver.findElement(By.xpath("//*[@id='au_submit_button2']/div[2]/a[1]/img")).click();//임시저장 클릭 Thread.sleep(3000); Alert alert = driver.switchTo().alert(); //얼럿 창 스위칭 alertText = alert.getText(); alert.accept(); //얼럿 확인 클릭 System.out.println("다른제목으로 "+alertText); String num = driver.findElement(By.id("temporary_save_count")).getText(); //임시저장 카운트 추출 System.out.println("임시저장 글 개수 : "+num); } @Test public void Step_04_이전_글_임시저장_삭제_Test () throws Exception { // 임시저장 창 driver.findElement(By.className("_tempsave_open_close")).click(); //임시저장 글 클릭 driver.switchTo().defaultContent(); //창 초기화 driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='editor']"))); //질문하기 iframe 창 스위칭 String info = driver.findElement(By.className("info_tempsave")).getText(); //임시저장 창 안내 글 추출 System.out.println("임시저장 창 " + info); WebElement tempList = driver.findElement(By.className("tempsave_list")); //임시저장 글 목록 가져옴 List<WebElement> list = tempList.findElements(By.className("q_on")); //목록을 리스트에 넣어둠 //이전 글이니까 2번째인 1번 목록 삭제 버튼을 클릭 list.get(1).findElement(By.tagName("img")).click(); Thread.sleep(3000); Alert alert = driver.switchTo().alert(); //삭제 확인 얼럿 창 alertText = alert.getText(); alert.accept(); //확인 클릭 System.out.println("이전" + alertText); } @Test public void Step_05_임시저장_삭제_Test () throws Exception { /*******이전 글 삭제와 동일*******/ driver.switchTo().defaultContent(); driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='editor']"))); WebElement tempList1 = driver.findElement(By.className("tempsave_list")); List<WebElement> list1 = tempList1.findElements(By.className("q_on")); //여기서 현재글 삭제를 위해 1번째인 0번째 목록 삭제버튼 클릭 list1.get(0).findElement(By.tagName("img")).click(); Thread.sleep(3000); Alert alert = driver.switchTo().alert(); alertText = alert.getText(); alert.accept(); System.out.println(alertText); Thread.sleep(1000); String num = driver.findElement(By.id("temporary_save_count")).getText(); System.out.println("임시저장 글 개수 : " + num); Thread.sleep(1000); } @AfterClass public static void tearDown() throws Exception { driver.quit(); } }
'지식메모 > 자동화' 카테고리의 다른 글
테스터로서 느낀 4가지 실수들 (0) | 2016.06.14 |
---|---|
appium 에서 특정영역을 좌우로 swipe 하기 (2) | 2016.05.23 |
Appium 자동화 상하좌우 스크롤 하기 (0) | 2016.03.23 |
Robotium API 기능 알아보기 (0) | 2016.02.18 |
로보티움 튜토리얼 실행해보기 (0) | 2015.09.04 |