如何通过GetElementByClass选择一个类并以编程方式单击它

Nig*_*ce2 6 html c# browser ajax webbrowser-control

我一直在尝试使用此代码在html/ajax中按类读取元素,因为知道GetElementByClass不是webBrowser.Document中的选项.我似乎无法获得返回值然后调用该成员.有没有解决这个问题?

参考: 按类名获取HTMLElements

例:

<span class="example">(<a href="http://www.test.com/folder/remote/api?=test" onclick=" return do_ajax('popup_fodder', 'remote/api?=test', 1, 1, 0, 0); return false; " class="example">test</a>)</span>
Run Code Online (Sandbox Code Playgroud)

示例代码:

   HtmlElementCollection theElementCollection = default(HtmlElementCollection);
   theElementCollection = webBrowser1.Document.GetElementsByTagName("span");
   foreach (HtmlElement curElement in theElementCollection)
   {
        //If curElement.GetAttribute("class").ToString = "example"  It doesn't work.  
        // This should be the work around.
        if (curElement.OuterHtml.Contains("example"))
        {
            MessageBox.Show(curElement.GetAttribute("InnerText")); // Doesn't even fire.
            // InvokeMember(test) after class is found.
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 15

我承认它不是很直观,但你需要使用GetAttribute("className")而不是GetAttribute("class")

HtmlElementCollection theElementCollection = default(HtmlElementCollection);
theElementCollection = webBrowser1.Document.GetElementsByTagName("span");
foreach (HtmlElement curElement in theElementCollection)
{
    if (curElement.GetAttribute("className").ToString() == "example")
    {
        MessageBox.Show(curElement.GetAttribute("InnerText")); // Do something you want
    }
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*iev 0

为什么不使用 qjuery 的选择器引擎呢?另外,您期望 messagebox.show 出现在哪里?

  • 太棒了,jquery 的一个分支?;) (3认同)