driver.get("https://twitter.com/");
//id
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"react-root\"]/div/div/div/main/div/div/div/div[1]/div[1]/div/form/div/div[3]/div")));
WebElement id = driver.findElement(By.xpath("//*[@id=\"react-root\"]/div/div/div/main/div/div/div/div[1]/div[1]/div/form/div/div[1]/div/label/div/div[2]/div/input"));
id.clear();
id.sendKeys(twitterID);
//pw
WebElement pw = driver.findElement(By.name("session[password]"));
pw.clear();
pw.sendKeys(twitterPW);

Thread.sleep(1000);
//login
WebElement login = driver.findElement(By.xpath("//*[@id=\"react-root\"]/div/div/div/main/div/div/div/div[1]/div[1]/div/form/div/div[3]/div"));
login.click();
Thread.sleep(500);

  1. 로그인 코드

  트위터 웹 페이지로 접속 후 ID칸에는 ID를, PW칸에는 PW를 넣고 로그인 버튼을 클릭하는 간단한 코드이다.

 

이런 것들

  문제점 : Selenium은 테스트 등을 자동화하기 위한 도구로서, 같은 동작을 수회~수십회 반복해야하는 경우가 많다.

  그리고 트위터 포함 많은 웹 사이트는, 올바른 ID/PW로 로그인하더라도 단기간에 로그인이 반복되면 이상으로 간주, 추가 인증을 요구한다

 

File file = new File("Twitter.data");
try {
	file.createNewFile();
	BufferedWriter bw = new BufferedWriter(new FileWriter(file));
	for(Cookie cookie : driver.manage().getCookies()) {
		bw.write((cookie.getName() + ";" + cookie.getValue() + ";"
			+cookie.getDomain() + ";" + cookie.getPath() + ";"
			+ cookie.getExpiry() + ";" + cookie.isSecure()));

		bw.newLine();
	}
	bw.close();
}catch (Exception e) {
	e.printStackTrace();
}

  2. 쿠키 저장

  기본적으로 Selenium으로 뭔갈하려 하면, 매 실행마다 새로운 크롬 창을 실행하게 된다.

  즉 '로그인 유지' 같은걸 체크한다 한들 이전에 로그인했던 정보는 사라진다는 뜻이다.

 

  로그인은 세션으로 관리되는데, 결국 세션은 쿠키로 저장되므로(맞나?) 쿠키를 따로 파일에 저장해둔 후 이를 복구하면 세션이 유지되는 효과를 볼 수 있다.

 

  위 코드는 driver에서 쿠키를 가져와 Twitter.data에 저장하는 코드이다.

  driver가 twitter.com을 지정하고 있으므로, 많은 쿠키들 중 트위터 관련 쿠키만 반환되어 저장되는 듯 하다.

  (트위터 관련 쿠키의 도메인 값은 twitter.com, .twitter.com 두가지를 확인할 수 있었다)

 

driver.get("https://twitter.com/");

File file = new File("Twitter.data");
BufferedReader br = new BufferedReader(new FileReader(file));

String readLine;
while((readLine = br.readLine())!=null) {
	StringTokenizer st = new StringTokenizer(readLine,";");
	String name = st.nextToken();
	String value = st.nextToken();
	String domain = st.nextToken();
	String path = st.nextToken();
	Date expiry = null;
	
	String val;
	if(!(val = st.nextToken()).equals("null")){
		System.out.println(val);
		SimpleDateFormat format =new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		expiry = format.parse(val);
	}
	Boolean isSecure = new Boolean(st.nextToken()).booleanValue();
	Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
	System.out.println(cookie);
	driver.manage().addCookie(cookie);
}
br.close();

driver.get("https://twitter.com/");

  3. 쿠키 복원

  새로운 selenium연결을 하고자 할 때, 1번처럼 직접 로그인하는 대신, 2번에서 저장한 파일을 불러와 쿠키를 복구할 수 있다.

  시간이 지나 expiry값이 만료됨에 따라 재 로그인이 필요할수도 있겠지만, 매번 로그인하는것보단 훨씬 효율적으로 사용 가능하다.

 

  File을 불러오기 전에 twitter에 한번 접속하는 이유는 addCookie 메소드가 현재 url이 cookie의 domain값과 일치해야 하기 때문이라고 한다 (출처)

  아무튼 한번 접속해주지 않으면 invalid cookie domain 에러를 받게 된다

 

작동 화면

  직접 실행해보면, 로그인 입력 없이도 잘 작동하는걸 확인할 수 있다.

 

  (왜인지 움짤 길이가 잘린다.. 여기서 확인 가능하다)

+ Recent posts