How to select a class by GetElementByClass and click on it programmatically

拈花ヽ惹草 提交于 2019-11-28 12:23:23
Joe Terhune

I admit it's not very intuitive but you need to use GetAttribute("className") instead of 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
    }
}

this is a example of how i used the webbrowser control to find class specific elements and invoke Click on a link inside.

simplified >

   foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("li"))
        {
            // use contains() if the class attribute is 
            // class="page_item page-item-218 current_page_item"
            //this to be more on spot! >> if (item.OuterHtml.Contains("class=\"page_item"))
            // or
            if (item.OuterHtml.Contains("page_item"))
            {
                foreach (HtmlElement childItem in item.Children)
                {
                    if (childItem.TagName == "A")
                    {
                        //Click the link/Current element
                        childItem.InvokeMember("Click");
                        break;
                    }
                }
                break;
            }
        } 

does this way work ?..

it works for me right here.

or maybe i misunderstand your question?

Why don't you use qjuery's selector engine for this. And also, where are you expecting the messagebox.show to appear ?

Dim HtmlElementcolltwo As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("button")
        For Each eleme As HtmlElement In HtmlElementcolltwo
            ' Check the attributtes you want
            If eleme.GetAttribute("className") = "derrt_submit feed-zed-bff" Then
                'Check even the text if you want
                ' If elem.InnerText = "Sign In" Then
                'Invoke your event
                eleme.InvokeMember("click")
                'End If
            End If
        Next

This Also works instead of using "class" use "className"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!