2

Im trying to get Steam name from this page "https://steamcommunity.com/id/giogongadzee" via class name. here is html code:

<div class="profile_header_bg">

<div class="profile_header_bg_texture">

    <div class="profile_header">

        <div class="profile_header_content">

                            <div class="profile_header_centered_persona">
                <div class="persona_name" style="font-size: 24px;">
                    <span class="actual_persona_name">Ghongha</span>  <--- i want to get "Ghongha" in MessageBox.Show();

here is what i tried to do but not working...

private void GetInfo_Click(object sender, EventArgs e)
    {
        var links = webBrowser1.Document.GetElementsByTagName("a");
        foreach (HtmlElement link in links)
        {
            if (link.GetAttribute("className") == "actual_persona_name")
            {
                MessageBox.Show(link.InnerText);
            }
            else
            {
                MessageBox.Show("0");
            }
        }
    }

Help :/

  • That's a `` element, not an anchor, so: `var element = webBrowser1.Document.GetElementsByTagName("SPAN").OfType().FirstOrDefault(elm => elm.GetAttribute("className").Equals("actual_persona_name"));`. In case you'll need the Links collection next time, the WebBrowser already provides one by itself ([WebBrowser.Document.Links](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.htmldocument.links)), no need to recreate it. – Jimi Jun 09 '20 at 09:04
  • You should also apply this: [How can I get the WebBrowser control to show modern contents?](https://stackoverflow.com/a/38514446/7444103) before anything else. – Jimi Jun 09 '20 at 09:10

2 Answers2

1

I found a working answer here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/a22cafb7-f93c-4911-91ce-b305a54811fa/how-to-get-element-by-class-in-c

Get the "className" attribute.


static IEnumerable<HtmlElement> ElementsByClass(HtmlDocument doc, string className)
{
  foreach (HtmlElement e in doc.All)
    if (e.GetAttribute("className") == className)
      yield return e;
}
Skyfish
  • 119
  • 2
  • 4
1

this is an extension method :

  public static List<System.Windows.Forms.HtmlElement> GetElementsByClassName(this System.Windows.Forms.WebBrowser browser, string TagName, string Classname)
    {
        var list = new List<System.Windows.Forms.HtmlElement>();
        var elements = browser.Document.GetElementsByTagName(TagName);
        foreach (System.Windows.Forms.HtmlElement link in elements)
            if (link.GetAttribute("className") == Classname)
                list.Add(link);

        return list;
    }