【问题标题】:C# get element by nameC# 按名称获取元素
【发布时间】:2015-10-02 09:26:23
【问题描述】:

所以我已经弄清楚如何通过 id 获取元素,但我不知道如何通过名称获取元素。

private void SendData()
{
    webBrowser1.Document.GetElementById("textfield1")
        .SetAttribute("value", textBox1.Text);
    webBrowser1.Document.GetElementById("textfield2")
        .SetAttribute("value", textBox1.Text);
}

问题在于 HTML 中 textfield1 是一个 id,但 textfield2 是一个名称。所以我想弄清楚如何获得textfield2:

<html>
    <input type="text" id="textfield1" value="TEXT1"><br>
    <input type="text" name="textfield2" value="TEXT2"><br>
    <input type="submit" value="Submit">
</html>

【问题讨论】:

  • 什么是webBrowser1和Document?您使用的是什么库/框架?
  • @kai 这是一个简单的System.Windows.Forms.WebBrowser 和它的HtmlDocument。

标签: c# html getelementbyid getelementsbyname


【解决方案1】:

您可以获得HtmlElementCollection - 例如,使用GetElementsByTagName 方法。那么HtmlElementCollection就有GetElementsByName方法:

webBrowser1.Document
    .GetElementsByTagName("input")
    .GetElementsByName("textfield2")[0]
        .SetAttribute("value", textBox1.Text);

【讨论】:

    【解决方案2】:

    你可以使用HtmlElementCollection.GetElementsByName来取元素的值

    webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox1.Text);
    

    编辑

    foreach (HtmlElement he in webBrowser1.Document.All.GetElementsByName("textfield2"))
    {
        he.SetAttribute("value", textBox1.Text);
    }
    

    【讨论】:

    • 您确定代码按预期工作吗? .GetElementsByName 应该返回一个数组,所以你必须在 .SetAttribute 之前使用 [0] 还是我弄错了?
    • 由于某种原因,我没有这种方法...我使用的是 .NET 4.5。
    • HtmlDocument 不包含这样的方法,这不会编译。
    • webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox2.Text); webBrowser1.Document.GetElementsByName("login_button").InvokeMember("click");我试过了,但不能让它工作我要在我的代码中添加一些东西吗?
    • 嗨,webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox2.Text);将获取元素集合,而不是像 getelementbyid 中的单个元素。请尝试 webBrowser1.Document.GetElementsByName("textfield2")[0] .SetAttribute("value", textBox1.Text);如果不起作用,您可以发布错误代码的确切含​​义。我想知道 html 是否已完全加载。
    【解决方案3】:

    您不能直接按名称访问元素,但您可以通过首先查找输入标签来访问它,然后对结果进行索引以按名称查找标签。

    webBrowser1.Document.GetElementsByTagName("input")["textfield2"]
    

    或

    webBrowser1.Document
        .GetElementsByTagName("input")
        .GetElementsByName("textfield2")[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多