【问题标题】:To click a button with the class having many of the same class单击具有许多相同类的类的按钮
【发布时间】:2015-06-11 22:59:16
【问题描述】:

当单击WebBrowser 中的网页上的按钮时,我必须使用以下代码通过元素类来完成:

HtmlElementCollection classButton = WebBrowser1.Document.All;
foreach (HtmlElement element in classButton)
 {
   if (element.GetAttribute("className") == "button color")
    {
       element.InvokeMember("click");
    }
 }

我想点击类为button color但有十二个相同类的按钮,我想只模拟第一个的点击。

【问题讨论】:

  • 欢迎来到 StackOverflow!为什么你有十二个具有相同类名的按钮?如果您希望它只调用找到的第一个按钮上的点击,那么您可以在InvokeMember 调用之后在 foreach 循环中添加一个break;
  • 第二个答案不起作用,是否要给第二个或其他地方?

标签: c#


【解决方案1】:

我决定移动我的 cmets 作为答案。由于 juansanchez1993 只想模拟在具有相同类名的 12 个按钮中单击第一个按钮,因此简单的解决方案是在调用 InvokeMember 之后在 foreach 循环中添加按钮。这是我的意思的一个例子:

HtmlElementCollection classButton = WebBrowser1.Document.All;

foreach (HtmlElement element in classButton)
{
    if (element.GetAttribute("className") == "button color")
    {
       element.InvokeMember("click");
       break; //Add the break after the InvokeMember is called to only invoke the 1st button click.
    }
}

这是我在 cmets 中使用System.Linq 调用特定类按钮的意思:

HtmlElementCollection classButton = WebBrowser1.Document.All.Where(e => e.GetAttribute("className") == "button color") as HtmlElementCollection;

classButton[index].InvokeMember("click");

免责声明:我之前从未使用过HtmlElementCollection,因此如果您对此有疑问,请务必添加一些 cmets。

【讨论】:

  • 如果给第二个或其他地方?
  • 错误 i.imgur.com/lC0bzAF.png 错误 1 ​​'System.Windows.Forms.HtmlElementCollection' no contiene una definición de 'Where' ni se encontró ningún método de extensión 'Where' que acepte unprimer argumento de Tipo 'System .Windows.Forms.HtmlElementCollection' (¿falta una directiva de uso o una referencia de ensamblado?) Error 2 El nombre 'index' no existe en el contexto actual I put using System.Linq;
  • 第二个答案不起作用,是否要给第二个或其他地方?
  • 您可以将 HtmlElementCollection 转换为 List<HtmlElement> 吗?我 100% 确定 List<T> 可以使用 Where LINQ 方法。我不确定HtmlElementCollection,因为我以前从未使用过它。 This question 可能对你有帮助。
  • 我认为进展顺利但没有很好地提高他们的代码,可惜我对此了解不多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多