我正在使用下面的代码来填写用户名和密码到他们各自的网站登录表单中。
var
Doc: IHTMLDocument2;
I: Integer;
Element: OleVariant;
Elements: IHTMLElementCollection;
Sub: Variant;
begin
Doc := WebBrowser1.Document as IHTMLDocument2;
Elements := Doc.All;
for I := 0 to Elements.length - 1 do begin
Element := Elements.item(I, varEmpty);
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'TEXT') then begin
if (Element.name = 'user') then Element.value := 'theusername';
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'PASSWORD') then begin
if (Element.name = 'passwrd') then Element.value := 'thepassword';
end;
end;
Sub := WebBrowser1.Document;
Sub.frmLogin.Submit();
end;
end;有关各字段的信息:


当我运行代码时发生了什么:

如您所见,用户名部分工作,用户名被插入。然而,密码字段没有。
我做错了什么?
发布于 2017-08-09 16:20:51
很难从问题中的格式中看出这一点。下面是该代码的副本,具有--主观上更好的格式。您可能会注意到,end;在您使用Webbrowser1之前做了一些事情。这是您的end;s的关闭if,因此它们是嵌套的。并且无法找到密码字段,因为它不符合这两种条件。
虽然代码格式化是一个品味问题,但有些东西确实可以帮助避免麻烦,使代码更加可读性。
原版改格式:
var
Doc: IHTMLDocument2;
I: Integer;
Element: OleVariant;
Elements: IHTMLElementCollection;
Sub: Variant;
begin
Doc := WebBrowser1.Document as IHTMLDocument2;
Elements := Doc.All;
for I := 0 to Elements.length - 1 do begin
Element := Elements.item(I, varEmpty);
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'TEXT') then
begin
if (Element.name = 'user') then Element.value := 'theusername';
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'PASSWORD') then
begin
if (Element.name = 'passwrd') then Element.value := 'thepassword';
end;
end;
Sub := WebBrowser1.Document;
Sub.frmLogin.Submit();
end;
end;解决了逻辑问题:
var
Doc: IHTMLDocument2;
I: Integer;
Element: OleVariant;
Elements: IHTMLElementCollection;
Sub: Variant;
begin
Doc := WebBrowser1.Document as IHTMLDocument2;
Elements := Doc.All;
for I := 0 to Elements.length - 1 do begin
Element := Elements.item(I, varEmpty);
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'TEXT') then
begin
if (Element.name = 'user') then
Element.value := 'theusername';
end;
if (UpperCase(Element.tagName) = 'INPUT') and (UpperCase(Element.Type) = 'PASSWORD') then
begin
if (Element.name = 'passwrd') then
Element.value := 'thepassword';
end;
Sub := WebBrowser1.Document;
Sub.frmLogin.Submit();
end;
end;https://stackoverflow.com/questions/45595350
复制相似问题