2011년 3월 15일 화요일

HTML 페이지의 태그 사이를 유랑하기

* 폼에 TWebBrowser 가 하나 박혀 있고, 그 이름은 WebBrowser1 이라고 가정함.
HTML 페이지의 Form Element 전부 뒤지기
procedureTForm1.Button3Click(Sender: TObject);
const URL = 'http://www.daum.net';
var
Document: IHTMLDocument2;
Form: IHTMLFormElement;
ovElements: OleVariant;
i, j: Integer;
// 디버깅용 내부함수. 실제로 사용할 땐 외부에서 정의하고 사용하지만 여기서만...
procedureD(s: String);
begin
OutputDebugString(PChar(s));
end;
// ___________________________________________________________
begin
// 웹페이지 로딩
WebBrowser1.Navigate(URL);
whileWebBrowser1.readyState<>READYSTATE_COMPLETE doApplication.ProcessMessages;
Document:=WebBrowser1.Document asIHTMLDocument2;

ifDocument<>nil then begin // Document.Forms 모두 뒤지기 fori:=0toDocument.forms.Length-1do begin // 각 Form 의 Element 모두 뒤지기 Form:=IDispatch(Document.Forms.Item(i, 0)) asIHTMLFormElement;
ovElements:=Form.elements;
forj:=0 toovElements.Length-1do begin
try

// Form.name & Element name, type, value 출력 D(Form.name+' -> '+ovElements.item(j).Name+' ['+ovElements.item(j).type+'] = '+ovElements.item(j).value);
except on E:Exception do D('[Error] '+E.Message);
end;
end; // for j end; // for i end
else
D('Document=nil');
end;
응용편 - 피파온라인2 로그인하기 (피망)
ID, 비번 입력은 OleVariant 를 이용했고,
로그인 버튼 클릭, 로그인 확인은 IHTMLDocument2, IHTMLElementCollection, IHTMLElement 를 이용.
주의: 화면 상에 TWebBrowser 가 그려지고 있어야 함. ID 넣는 부분이 화면 밖으로 나가 있을 경우 로직은 통하지 않음.
procedureTForm1.Button4Click(Sender: TObject);
const
URL = 'http://fifaonline.pmang.com';
ID = '사용ID';
PW = '사용비번';
INPUT_NAME_ID = 'usrid';
INPUT_NAME_PW = 'passwd';
var Document: IHTMLDocument2;
elementcol: IHTMLElementCollection;
element: IHTMLElement;
Input: OleVariant;
i: Integer;
LoginComplete: Boolean;
begin
// 웹페이지 로딩
WebBrowser1.Navigate(URL);
whileWebBrowser1.readyState<>READYSTATE_COMPLETE doApplication.ProcessMessages;
// ID, 비밀번호 입력
Input:=WebBrowser1.OleObject.Document.Body.getElementsByTagName('input');
fori:=0toInput.Length-1do begin
// ID if(Input.Item(i).NAME=INPUT_NAME_ID) thenInput.Item(i).value:=ID;
// 비밀번호 if (Input.Item(i).NAME=INPUT_NAME_PW)thenInput.Item(i).value:=PW;
end;
// 로그인 버튼 클릭
Document:=WebBrowser1.Document asIHTMLDocument2;
Document.all.tags('input').QueryInterface(IHTMLElementCollection, elementcol);
fori:=0to elementcol.length-1do begin
element:=elementcol.item(i,0) asIHTMLElement;
ifSystem.Pos('btn_login', element.outerHTML)>0thenelement.click;
end;
// 로그인 완료될 때까지 대기 - 로그아웃 버튼이 있으면 로그인 완료 판단 LoginComplete:=False;
while notLoginComplete do begin Document.all.tags('img').QueryInterface(IHTMLElementCollection, elementcol);
for i:=0toelementcol.length-1do begin element:=elementcol.item(i, 0) asIHTMLElement;
ifPos('btn_logout', element.outerHTML)>0then begin
LoginComplete:=True;
break;
end; // if
end; // for
Sleep(500);
Application.ProcessMessages;
end; // while
end;

댓글 없음:

댓글 쓰기