0

我正在使用以下代码在网站登录表单上各自的字段中填写用户名和密码。

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;

各个字段的信息:

在此处输入图像描述 在此处输入图像描述

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

在此处输入图像描述

如您所见,用户名部分有效,用户名被插入。但是,密码字段没有。

我究竟做错了什么?

4

1 回答 1

2

问题中的格式很难看到这一点。以下是该代码的副本,主观上具有更好的格式。您可能会注意到,end;在您使用 Webbrowser1 做某事之前。那是end;您的 s 的结束 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;
于 2017-08-09T16:20:51.540 回答