首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TWebBrowser自动登录

TWebBrowser自动登录
EN

Stack Overflow用户
提问于 2017-08-09 15:49:53
回答 1查看 1.2K关注 0票数 0

我正在使用下面的代码来填写用户名和密码到他们各自的网站登录表单中。

代码语言:javascript
复制
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;

有关各字段的信息:

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

如您所见,用户名部分工作,用户名被插入。然而,密码字段没有。

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 16:20:51

很难从问题中的格式中看出这一点。下面是该代码的副本,具有--主观上更好的格式。您可能会注意到,end;在您使用Webbrowser1之前做了一些事情。这是您的end;s的关闭if,因此它们是嵌套的。并且无法找到密码字段,因为它不符合这两种条件。

虽然代码格式化是一个品味问题,但有些东西确实可以帮助避免麻烦,使代码更加可读性。

原版改格式:

代码语言:javascript
复制
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;

解决了逻辑问题:

代码语言:javascript
复制
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;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45595350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档