【问题标题】:Webbrowser SetAttribute not working (Password Field)Webbrowser SetAttribute 不起作用(密码字段)
【发布时间】:2010-11-24 17:38:10
【问题描述】:

试图编写一个程序,让我在 c# 的网络浏览器中自动登录。这是我目前为此目的使用的代码:

HtmlElementCollection pageTextElements = loginBrowser.Document.GetElementsByTagName("input");
        foreach (HtmlElement element in pageTextElements)
        {
            if (element.Name.Equals("username"))
                element.SetAttribute("value", this.UserName);
            if (element.Name.Equals("password"))
                element.SetAttribute("value", this.Password);
        }

它填写的是用户名,而不是密码? ): 谷歌搜索,但只有少数人提出了没有人回答的话题。 /:

希望有人可以帮助我。 这是密码字段的来源:

<input type="password" value="" maxlength="50" size="25" name="password" class="bginput">

【问题讨论】:

  • @Adam Maras 感谢您的澄清。删除我的答案,因为我对此没有任何建议。
  • 您是否在设置密码字段属性的行上设置了断点,只是为了看看它是否被命中?
  • 是的,我做到了。它被击中,执行,但根本不把密码放在盒子里。

标签: c# passwords browser setattribute


【解决方案1】:

以上方法都不适合我,我可以在 DocumentCompleted() 事件处理程序中的用户名文本框上调用 setAttribute(),但不能在密码文本框中调用。我最终通过以下方式让它工作:

HtmlElementCollection inputs = doc.GetElementsByTagName("input");
HtmlElement usr = inputs.GetElementsByName("username")[0];
usr.setAttribute("value", strUsername);

HtmlElement pwd = inputs.GetElementsByName("password")[0];
pwd.GotFocus += new HtmlElementEventHandler(pwd_GotFocus);
pwd.Focus();

然后在 onFocus 处理程序中:

void pwd_GotFocus(object sender, HtmlElementEventArgs e)
{
    HtmlElement pwd = (HtmlElement)sender;
    pwd.SetAttribute("value", strPassword);
}

我不知道为什么这个行得通而另一个不行。我只尝试更改密码,以防文档更改设置用户名干扰它。我什至创建了另一个 WebBrowser 控件,然后从源中获取 DocumentText,在第二个 WebBrowser 上设置 DocumentText 之前,在原始 html 中查找并替换设置密码值,但它再次没有正确设置值.

如果有人有的话,我很想知道一个更清洁的解决方案

【讨论】:

  • 这对我也有用!一直在尝试各种方法..这一步似乎有效。
【解决方案2】:

您需要等到文档更新完成。 DocumentCompleted 事件方法。

如果您想查看发生了什么,请创建一个顶部带有 Panel 底部的 WebBrowser 的表单。添加 3 个TextBoxes、一个Button 和另一个TextBox。下面框的OnClick 方法做了以下事情:

webBrowser1.Document.GetElementById(this.textBox1.Text).SetAttribute(this.textBox2.Text, this.textBox3.Text);
this.textBox4.Text = webBrowser1.Document.GetElementById(this.textBox1.Text).GetAttribute(this.textBox2.Text);

您会看到表单上的Password 框已正确填充。

韦恩

【讨论】:

    【解决方案3】:

    尝试像这样设置 innerText 属性,它适用于我(vb.net):

    Dim txtPassword As HtmlElement = browser.Document.GetElementById("ctl00_ContentPlaceHolder1_txtPassword")
    
    txtPassword.InnerText = "123456"
    

    【讨论】:

    • 通过将所有元素写入一个字符串并在那里将 &password= 更改为 &password=thepass ;) 解决了这个问题,谢谢大家 (:
    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多