【问题标题】:C# webBrowser1 How to get element by class?C# webBrowser1 如何按类获取元素?
【发布时间】:2020-09-28 07:57:32
【问题描述】:

我试图通过类名从此页面“https://steamcommunity.com/id/giogongadzee”获取 Steam 名称。这是html代码:

<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();

这是我试图做但没有工作的...

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");
            }
        }
    }

帮助:/

【问题讨论】:

  • 这是一个&lt;span&gt; 元素,而不是一个锚点,所以:var element = webBrowser1.Document.GetElementsByTagName("SPAN").OfType&lt;HtmlElement&gt;().FirstOrDefault(elm =&gt; elm.GetAttribute("className").Equals("actual_persona_name"));。万一您下次需要 Links 集合,WebBrowser 已经自己提供了一个(WebBrowser.Document.Links),无需重新创建。

标签: c# webbrowser-control getelementsbyclassname


【解决方案1】:

我在这里找到了一个可行的答案: 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-03-07
    相关资源
    最近更新 更多